1 //去基准数 为首元素,为元素和 处于中间元素值的中位数 2 ElementType median(ElementType a[], int left, int right) { 3 int center = (left + right) / 2; 4 5 if (a[left] > a[center]) swap(&a[left], &a[right]); 6 if (a[left] > a[right]) swap(&a[left], &a[right]); 7 if (a[center] > a[right]) swap(&a[center], &a[right]); 8 swap(&a[center], &a[right - 1]);//将基本pivot存在右边 9 //下面只需考虑a[left+1]--a[right-2] 10 return a[right - 1]; 11 } 12 13 void quickSort(ElementType a[], int left, int right) { 14 int pivot, low, high; 15 16 pivot = midian(a, left, right); 17 low = left; high = right - 1; 18 while (1) { 19 //将序列中比基本小的移到左边,大的移到右边 20 while (a[++low] < pivot); 21 while (a[--high] > pivot); 22 if (low < high) swap(&a[low], &a[high]); 23 else break; 24 } 25 26 swap(&a[low], &a[right - 1]);//将基准换到正确的位置 27 quickSort(a, left, low - 1);//递归解决左边 28 quickSort(a, low + 1, right); 29 }