快速排序用到了分治、和递归的思想,感觉挺有趣。
基本算法:
1).选择一个基准元素,通常选择第一个元素。
2).通过一趟排序将待排序的记录分割成独立的两部分,其中一部分记录的元素值均比基准元素值小 "左子树"。另一部分记录的元素值比基准值大 "右子树"。
3).此时基准元素在其排好序后的正确位置,"树的根节点"。
4).然后分别对 左子树和右子树进行同样的排序操作,直到整个序列有序。
void swap_1_1(int *a,int *b){
*a^=*b^=*a^=*b;
}
//获得中轴的位置
//升序排序
int partition_1_1(int a[],int low ,int high){
//假定基数是a[low]
int privotkey = a[low];
while (low < high) {
while (low < high &&a[high]>= privotkey) {
high --;
}
if (a[low] >a[high]) {
swap_1_1(&a[low], &a[high]);//将左边比右边大的记录交换
}
while (low < high&&a[low] <= privotkey) {
low++;
}
if (a[low] > a[high]) {
swap_1_1(&a[low], &a[high]);//将左边比右边大的记录交换
}
}
//外层的low = high 时退出,但是起初进入函数时 low < high,过程中,high必定自减,或者low自加 即操作Operation1 = high--,Operation2 = low++; 逻辑表达式(Operation1||Operation2)必定是YES
return low;
}
void quickSort1_1(int a[],int low,int high){
if (low < high) {
//获得中轴位置
int privotLocition = partition_1_1(a,low,high);//将主树划分成,左子树和右子树,树的根节点即中轴的元素,左子树的所有值,小于右子树的所有值
quickSort1_1(a,0,privotLocition-1);//对左子树继续划分
quickSort1_1(a,privotLocition+1, high);//对右子树继续划分
}
}
主函数调用
int main(int argc, const char * argv[]) {
@autoreleasepool {
// insert code here...
int a[5] = {3,1,5,7,8};
printf("初始值");
print(a,5);
quickSort1_1(a,0,4);
printf("\n结果\n");
print(a,5);
}
return 0;
}