OC冒泡排序算法


面試的時候很多公司會要求寫一個冒泡排序算法,於是用OC寫了一個,代碼如下所示

需要注意的事項:oc數組只能存放oc對象,因此遍歷數組輸出的時候,記得通過NSString對象轉換成intValue

   #import <Foundation/Foundation.h>

   void bubleSort(NSMutableArray *numbers){
   int i,j,count= (int)[numbers count];

   for (i = 0; i < count; i++) {
      for (j = i+1; j<count; j++) {
         int a = [[numbers objectAtIndex:i] intValue];
         int b = [[numbers objectAtIndex:j] intValue];
        
         if (a>b) { //從小到大
             [numbers replaceObjectAtIndex:i withObject:[NSString stringWithFormat:@"%d",b]];
             [numbers replaceObjectAtIndex:j withObject:[NSString stringWithFormat:@"%d",a]];
          }
       }
    }

   for (NSString *num in numbers) {
         NSLog(@"%d",[num intValue]);
    }
 }


int main(int argc, const char * argv[]) {
    @autoreleasepool {
         NSMutableArray *p = [[NSMutableArray alloc] initWithObjects:@"3",@"6",@"4",@"5",@"1",@"2", nil];
        bubleSort(p);
     }
   return 0;
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM