Quick sort algorithm is quite like the merge sort, cause both of them use the idea of divide-and-conquer, but be aware, quick sort doesn't conquer it subproblems, cause when the problem is divided into small enough (only 1 element in the sub array), the whole array have already been sorted.
The worst case running time of quick sort is O(n^2), this can happen when the array is already sorted, so the total running time is T(n) = T(n-1) + /theta(n), and we can have T(n) =O(n^2). To avoid such case, we can randomly pick one as the pivot and swap it with the last element in the array, and the running time will be O(n lgn).
class QuickSortAlgorithm { public void QuickSort(int[] array, int begin, int end) { if (begin < end) { int partitionPosition = Partition(array, begin, end); //get the pivot position, and divide. QuickSort(array, begin, partitionPosition - 1); // the left part of the array. QuickSort(array, partitionPosition + 1, end); // the right part of the array. } } /// <summary> /// The reason to use random pivot is to prevent O(n^2) running time. /// </summary> /// <param name="array"></param> /// <param name="begin"></param> /// <param name="end"></param> /// <returns></returns> public int Partition(int[] array, int begin, int end) { Random rd = new Random(Guid.NewGuid().GetHashCode()); int tempPivot = rd.Next(begin, end); Swap(tempPivot, end, array); int pivot = array[end]; int startPoint = begin - 1; for (int j = begin; j < end; j++) { if (array[j] < pivot) { startPoint++; Swap(startPoint, j, array); } } Swap(end, startPoint + 1, array); return startPoint + 1; } private void Swap(int p1, int p2, int[] array) { int temp = array[p1]; array[p1] = array[p2]; array[p2] = temp; } }
Reference:
http://blog.youkuaiyun.com/atlasroben/archive/2008/07/29/2729301.aspx