快速排序
快速排序与归并排序一样基于分治法,但其执行partition进行分割时就已经在原属组完成了排序。
代码如下
#import <Foundation/Foundation.h>
#include <stdio.h>
int a[101] , n;
void quickSort(int left, int right) {
int i, j, t, temp;
if (left > right)
return ;
temp = a[left]; //temp 存储的是基准数
i = left;
j = right;
while (i != j) {
while (a[j] >= temp && i < j) {
j--;
}
while (a[i] <= temp && i < j) {
i++;
}
if (i < j) {
t = a[i];
a[i] = a[j];
a[j] = t;
}
}
a[left] = a[i];
a[i] = temp;
quickSort(left, i-1);
quickSort(i+1 , right);
return ;
}
int main(int argc, const char * argv[]) {
@autoreleasepool {
int i;
scanf("%d", &n);
for (int i = 1; i < n; i++) {
scanf("%d", &a[i]);
}
quickSort(1, n);
for (i = 1; i < n; i++) {
NSLog(@"%d",a[i]);
}
}
return 0;
}