美文网首页Objective-Cios编程算法
Objective-C实现常用的排序算法

Objective-C实现常用的排序算法

作者: KaiweiWu | 来源:发表于2015-02-09 22:11 被阅读341次

    一、冒泡排序:

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

    二、选择排序:

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

    三、快速排序:

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

    相关文章

      网友评论

      本文标题:Objective-C实现常用的排序算法

      本文链接:https://www.haomeiwen.com/subject/vwsjxttx.html