2011-10-01 47 views
1

我是Mac上編程的新手(即xcode和cocoa),我試圖簡單地執行一個冒泡排序,並且遇到很多困難。如何對可可中的整數數組進行排序?

這樣做的目標是通過使用9像素內核使用中值濾波器來過濾圖像。我採用所有九個像素的灰度值,然後我試圖把它們放在一個九點數組中,並對數組進行排序以提取九個像素的中值(因此,如果使用上升或下降無關緊要)。

我一直在嘗試將像素值(這是整數)存儲到NSMutableArray,但我真的不知道如何去做這個或如何在數組填充時對它們進行排序。

// 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];     
      } 
     } 
    } 

回答

1

如何對可可中的整數數組進行排序?

int爲C型,因此,以相同的方式如在C.

的Mac OS X附帶在標準庫若干排序功能。由Quicksort定義的qsort由C定義;其他人來自BSD。他們都在qsort's manpage之下。

的功能中的每取指針大小元件的陣列,所以你想使用long(或者,對於更便攜,intptr_t),不int,對於元件。

製作一個這樣的元素的C數組,手動填寫,然後用這些函數之一進行排序並找到中值。

1

,以填補他們爲NS(Mutable)Array您需要的NSNumber實例來包裝你int S,如:

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

有多種方法所得到的數組進行排序,讓你開始:

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

幸運的是,這不使用BubbleSort。

相關問題