Time complexity:
Worst-case: \(O(n^2)\)
Best-case: \(O(nlog(n))\)
Average-case: \(O(nlog(n))\)
Pick a random element (pivot) and partition the array.
[all numbers that are less than the pivot] pivot [all numbers that are greater than the pivot]
Version 1.
void QuickSort(int *list, int size) { sortStep(list, size, 0, size-1); } int partition(int *list, int size, int left, int right, int pivotIndex) { int pivot = list[pivotIndex]; int i, index = left; swap(&list[right], &list[pivotIndex]); for(i=left;i<right;i++) { if(list[i] < pivot) { swap(&list[index++],&list[i]); } } swap(&list[index], &list[right]); return index; } void sortStep(int *list, int size, int left, int right) { if(left < right) { //pick up a pivot srand(time(NULL)); int pivotIndex = rand()%(right-left+1) + left; // make sure the range you set is correct int index = partition(list, size, left, right, pivotIndex); sortStep(list, size, left, index-1); sortStep(list, size, index+1, right); } }
Version 2.
void QuickSort(int *list, int size) { sortStep(list, size, 0, size-1); } int partition(int *list, int size, int left, int right, int pivotIndex) { if(left < right) { int i, j, leftIndex=left, rightIndex=right; while(list[leftIndex] < list[pivotIndex]) leftIndex++; while(list[rightIndex] > list[pivotIndex]) rightIndex--; while(leftIndex < rightIndex) { swap(&list[leftIndex], &list[rightIndex]); leftIndex++; rightIndex--; while(list[leftIndex] < list[pivotIndex]) leftIndex++; while(list[rightIndex] > list[pivotIndex]) rightIndex--; } swap(&list[rightIndex], &list[pivotIndex]); return rightIndex; } } void sortStep(int *list, int size, int left, int right) { if(left < right) { //pick up a pivot int pivotIndex = left; //set first element as our pivot int index = partition(list, size, left, right, pivotIndex); sortStep(list, size, left, index-1); sortStep(list, size, index+1, right); } }