快速排序

来源:互联网 发布:网络兼职文案 编辑:程序博客网 时间:2024/06/05 13:30

//

//  ViewController.m

//  QuickSort2015127

//

//  Created by apple on 15/12/7.

//  Copyright © 2015 apple. All rights reserved.

//


#import "ViewController.h"


@interface ViewController ()


@end


@implementation ViewController


- (void)viewDidLoad {

    [superviewDidLoad];

    // Do any additional setup after loading the view, typically from a nib.

    

    int arr[10] = {12,36,47,58,160,41,43,93,148,12};

    quickSort(arr, 0, 9);

    printf("\n");

    printArr(arr);

    

}

void printArr(int *a) {

    

    for (int k =0 ; k < 10; k++) {

        printf("%d-",a[k]);

    }

    printf("\n");

}


void quickSort(int *a,int left ,int right) {

    

    if (left < right) {

        int i =  partionIndex(a, left, right);

        quickSort(a, left, i - 1);

        quickSort(a, i +1,right);

        

    }

    

    

}



int partionIndex(int *a,int left ,int right){

    

    int i = left;

    int j = right;

    int temp = a[left];

    

    while (i < j) { //只有满足这个条件就一直循环

        //在右边找一个比temp小或者等的

        while (i  < j) {

            

            if (temp > a[j]) { // 找到了跳出循环

                

                a[i] = a[j]; //赋值给它

                i ++; //通知左边开始左边的++操作

                break;//一定要退出

            }else {

                j -- ;

            }

            

        }

        

        // 在左边找到一个比temp 要大的数

        while (i < j) {

            

            if (temp < a[i]) {//找到了

                

                a[j] = a[i];

                j--; // 通知右边开始右边的 --操作

                break;//一定要退出

                

            }else {

                i ++;

            }

            

        }

        

        

        

    }

    

    a[i] = temp;

    return i;

    

}



@end



0 0
原创粉丝点击