diff --git a/快速法.cpp b/快速法.cpp index e52d01b..b6046c2 100644 --- a/快速法.cpp +++ b/快速法.cpp @@ -1,35 +1,76 @@ 6.快速排序 6.1 描述 -oid quick(int *a,int i,int j) -{ - int m,n,temp; - int k; - m=i; - n=j; - k=a[(i+j)/2]; - do - { - while( a[m]k && n>i ) - n--; - - if(m<=n) - { - temp=a[m]; - a[m]=a[n]; - a[n]=temp; - m++; - n--; - } - } - while(m<=n); - - if(mi) - quick(a,i,n); +快速排序使用分治法来把一个串(list)分为两个子串(sub-lists)。具体算法描述如下: +(1)从数列中挑出一个元素,称为 “基准”(pivot); +(2)重新排序数列,所有元素比基准值小的摆放在基准前面,所有元素比基准值大的摆在基准的后面(相同的数可以到任一边)。 + 在这个分区退出之后,该基准就处于数列的中间位置。这个称为分区(partition)操作; +(3)递归地(recursive)把小于基准值元素的子数列和大于基准值元素的子数列排序。 + +6.2 复杂程度 +时间复杂度O(nlog2n) +空间复杂度O(nlog2n) + +6.3 代码 + +#include +void Swap(int *, int *); //函数声明, 交换两个变量的值 +void QuickSort(int *, int, int); //函数声明, 快速排序 + +int main(void) +{ + int i; //循环变量 + int a[] = {22, 34, 3, 32, 82, 55, 89, 50, 37, 5, 64, 35, 9, 70}; + QuickSort(a, 0, 14); + printf("最终排序结果为:\n"); + for (i=0; i<14; ++i) + { + printf("%d ", a[i]); + } + printf("\n"); + return 0; } +void Swap(int *p, int *q) +{ + int buf; + buf = *p; + *p = *q; + *q = buf; + return; +} +void QuickSort(int *a, int low, int high) +{ + int i = low; + int j = high; + int key = a[low]; + if (low >= high) //如果low >= high说明排序结束了 + { + return ; + } + while (low < high) + { + while (low < high && key <= a[high]) + { + --high; + } + if (key > a[high]) + { + Swap(&a[low], &a[high]); + ++low; + } + while (low < high && key >= a[low]) + { + ++low; + } + if (key < a[low]) + { + Swap(&a[low], &a[high]); + --high; + } + } + QuickSort(a, i, low-1); //用同样的方式对分出来的左边的部分进行同上的做法 + QuickSort(a, low+1, j); //用同样的方式对分出来的右边的部分进行同上的做法 +} + +6.4 运行时间 + 0.02485s