如何在可可中对一组int进行排序?

时间:2011-10-01 17:26:49

标签: arrays cocoa

我是Mac上的编程新手(即xcode和cocoa),我只想简单地执行冒泡排序并且遇到很多困难。

这样做的目的是使用9像素内核使用中值滤波器过滤图像。我接受了所有九个像素的灰度值,然后我试图将它们放在九点阵列中并对数组进行排序以提取九个中值(所以如果我使用升序或降序则无关紧要)。

我一直在尝试将像素值(即整数)存储到NSMutableArray中,但我真的不知道如何执行此操作或如何在填充数组时对它们进行排序。< / p>

    // Perform median filter on all images in the stack 
    for (x = 0; x < [curPix pwidth]; x++){
        for (y = 0; y < [curPix pheight]; y++){

            float value;
            int tLeft, tMid, tRight, cLeft, index, cRight, bLeft, bMid, bRight; // takes in pixel placement
            value = tLeft = tMid = tRight = cLeft = index = cRight = bLeft = bMid = bRight = 0;
            curPos = y * [curPix pwidth] + x;

            if (x != 0 && y != 0 && x != ([curPix pwidth]-1) && y != ([curPix pheight]-1)){

                //Make kernel for median filter
                index   = fImage[curPos];                       // index pixel
                tLeft   = fImage[index - [curPix pwidth] - 1];  // top left
                tMid    = fImage[index - [curPix pwidth]];      // top middle
                tRight  = fImage[index - [curPix pwidth] + 1];  // top right
                cLeft   = fImage[index - 1];                    // center left
                cRight  = fImage[index + 1];                    // center right
                bLeft   = fImage[index + [curPix pwidth] - 1];  // bottom left
                bMid    = fImage[index + [curPix pwidth]];      // bottom middle
                bRight  = fImage[index + [curPix pwidth] + 1];  // bottom right

                // Need to make array, populate with pixels (above), and sort.
                // Once sorted, take median value, save it as 'value', and store it as new pixel value

                fImage[curPos] = (int) value;   // return value to index
            }
            else {
                fImage[curPos] = fImage[curPos];                
            }
        }
    }

3 个答案:

答案 0 :(得分:1)

  

如何在可可中对一组int进行排序?

int是C类型,因此与C中的方式相同。

Mac OS X在标准库中附带了许多排序功能。 qsort,即Quicksort,由C定义;我想,其他人来自BSD。他们都在qsort's manpage之下。

每个函数都使用一个指针大小的元素数组,因此您需要使用long(或者,为了更具可移植性,intptr_t),而不是int,元素。

制作一个这样的元素的C数组,手动填写,然后使用其中一个函数排序并找到中位数。

答案 1 :(得分:1)

要将它们填入NS(Mutable)Array,您需要将int包裹在NSNumber的实例中,例如:

NSMutableArray *myArray = [NSMutableArray array];
[myArray addObject:[NSNumber numberWithInt:42]];

有多种方法可以对结果数组进行排序,以便开始使用:

[myArray sortUsingSelector:@selector(compare:)];

幸运的是,这不使用BubbleSort。

答案 2 :(得分:0)

首先,除非您要对小样本进行分类,否则我会避开气泡排序。冒泡排序非常慢。不是可可专家,除了建议您查看内置的数组排序例程之外,我不能真正帮助你。

这适用于iphone,但可能有所帮助: http://www.iphonedevsdk.com/forum/iphone-sdk-development/61615-how-do-i-sort-30-000-objects.html

祝你好运。