1. 程式人生 > >用objective-c 實現常用演算法(冒泡、選擇、快速、插入)

用objective-c 實現常用演算法(冒泡、選擇、快速、插入)

原文網址:http://www.360doc.com/content/14/0508/15/11029609_375813213.shtml

研究了下用oc實現常用的演算法,參考了一些資料後自己用程式碼檢驗了下,以下程式碼均測試可用。其中arr引數是一個可變陣列,其中存的是NSNumber型別的資料,具體如下:

<span style="font-size:14px;">NSArray *arr = @[[NSNumber numberWithInt:10],[NSNumber numberWithInt:1],[NSNumber numberWithInt:3],[NSNumber numberWithInt:12],[NSNumber numberWithInt:22],[NSNumber numberWithInt:5],[NSNumber numberWithInt:33]];  
NSMutableArray *oldArr = [[NSMutableArray alloc]initWithArray:arr];  
NSLog(@"排序前:%@",oldArr); </span>

.氣泡排序

- (void)sort:(NSMutableArray *)arr  
{  
    for (int i = 0; i < arr.count; i++) {  
        for (int j = 0; j < arr.count - i - 1;j++) {  
            if ([arr[j+1]integerValue] < [arr[j] integerValue]) {  
                int temp = [arr[j] integerValue];  
                arr[j] = arr[j + 1];  
                arr[j + 1] = [NSNumber numberWithInt:temp];  
            }  
        }  
    }  
    NSLog(@"氣泡排序後:%@",arr);  
} <strong> 
</strong>


.選擇排序

- (void)sort:(NSMutableArray *)arr  
{  
    for (int i = 0; i < arr.count; i ++) {  
        for (int j = i + 1; j < arr.count; j ++) {  
            if ([arr[i] integerValue] > [arr[j] integerValue]) {  
                int temp = [arr[i] integerValue];  
                arr[i] = arr[j];  
                arr[j] = [NSNumber numberWithInt:temp];  
            }  
        }  
    }  
      
    NSLog(@"選擇排序後:%@",arr);  
}  


.快速排序

- (void)quickSort:(NSMutableArray *)arr leftIndex:(int)left rightIndex:(int)right  
{  
    if (left < right) {  
        int temp = [self getMiddleIndex:arr leftIndex:left rightIndex:right];  
        [self quickSort:arr leftIndex:left rightIndex:temp - 1];  
        [self quickSort:arr leftIndex:temp + 1 rightIndex:right];  
    }  
}  
  
- (int)getMiddleIndex:(NSMutableArray *)arr leftIndex:(int)left rightIndex:(int)right  
{  
    int tempValue = [arr[left] integerValue];  
    while (left < right) {  
        while (left < right && tempValue <= [arr[right] integerValue]) {  
            right --;  
        }  
        if (left < right) {  
            arr[left] = arr[right];  
        }  
          
        while (left < right && [arr[left] integerValue] <= tempValue) {  
            left ++;  
        }  
        if (left < right) {  
            arr[right] = arr[left];  
        }  
    }  
    arr[left] = [NSNumber numberWithInt:tempValue];  
    return left;  
}  


.插入排序

- (void)sort:(NSMutableArray *)arr  
{  
    for (int i = 1; i < arr.count; i ++) {  
        int temp = [arr[i] integerValue];  
          
        for (int j = i - 1; j >= 0 && temp < [arr[j] integerValue]; j --) {  
            arr[j + 1] = arr[j];  
             arr[j] = [NSNumber numberWithInt:temp];  
        }  
         
          
    }  
    NSLog(@"插入排序後:%@",arr);  
}