快速排序(Quick Sort)算法的实现

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值