快速排序实现
来源:互联网 发布:贵州大数据局地址 编辑:程序博客网 时间:2024/06/03 22:55
快速排序的原理见http://en.wikipedia.org/wiki/Quicksort
快速排序采用分而治之的策略,即partition-sort。先对待排序的序列进行partition操作,即从序列中选择一个基准值(pivot),将序列中的元素与基准值比较,排序(sort)成小于和大于基准值的两个序列;再从两个序列中分别选择新的基准值,对两个序列再进行排序;直至整个序列不能再分,完成总体的排序。
假设序列的长度为N,需进行x次partition-sort,则有2^x=N,则快速排序的时间复杂度为O(logN)。
In-place快速排序不需要额外的存储空间,其实现伪代码为:
// left is the index of the leftmost element of the array // right is the index of the rightmost element of the array (inclusive) // number of elements in subarray = right-left+1 function partition(array, 'left', 'right', 'pivotIndex') 'pivotValue' := array['pivotIndex'] swap array['pivotIndex'] and array['right'] // Move pivot to end 'storeIndex' := 'left' for 'i' from 'left' to 'right' - 1 // left ≤ i < right if array['i'] < 'pivotValue' swap array['i'] and array['storeIndex'] 'storeIndex' := 'storeIndex' + 1 swap array['storeIndex'] and array['right'] // Move pivot to its final place return 'storeIndex'
function quicksort(array, 'left', 'right') // If the list has 2 or more items if 'left' < 'right' // See "Choice of pivot" section below for possible choices choose any 'pivotIndex' such that 'left' ≤ 'pivotIndex' ≤ 'right' // Get lists of bigger and smaller items and final position of pivot 'pivotNewIndex' := partition(array, 'left', 'right', 'pivotIndex') // Recursively sort elements smaller than the pivot quicksort(array, 'left', 'pivotNewIndex' - 1) // Recursively sort elements at least as big as the pivot quicksort(array, 'pivotNewIndex' + 1, 'right')
下图是in-place快速排序的示意图:
In-place partition in action on a small list. The boxed element is the pivot element, blue elements are less or equal, and red elements are larger.
实现代码为:
void my_swap(int& a, int& b){int temp = a;a = b;b = temp;}int partition(int* a, int left, int right){int pivotIndex = (left + right) / 2;int pivotValue = a[pivotIndex];my_swap(a[pivotIndex], a[right]);int storedIndex = left;for( int i = left; i < right; i++ ){if( a[i] < pivotValue ){my_swap( a[i], a[storedIndex] );storedIndex ++;}}my_swap( a[right], a[storedIndex] );return storedIndex;}int quick_sort( int* a, int left, int right ){if( left < right ){int index = partition(a, left, right);quick_sort(a, left, index-1);quick_sort(a, index+1, right);}else{return 1;}}
- 快速排序算法实现
- 快速排序的实现
- java实现快速排序
- 快速排序---c#实现
- 快速排序算法实现
- 快速排序Java实现
- 快速排序算法实现
- 快速排序java实现
- 快速排序JAVA实现
- AWK快速排序实现
- Java实现快速排序
- 快速排序实现
- 数组实现快速排序
- 快速排序的实现
- 快速排序--Java实现
- 递归实现快速排序
- 快速排序java实现
- C#实现快速排序
- Java虚拟机运行机制(转)
- 字符串转换为整型数字(C#)
- ubuntu下pig-0.9.2伪分布配置
- 如果编程语言是一条船…
- Android中定时器Timer和TimerTask的启动,停止,暂停,继续等操作实例
- 快速排序实现
- Asp.net的编码好习惯
- 关于深度学习(Deep Learning) ....2004年
- 64位Win7安装不能上网问题解决
- Drupal 7在Redhat上的模块安装
- 机器学习——深度学习(Deep Learning)
- [转] 送给优柔寡断和胡思乱想的朋友们---17条人生哲理
- 报表导出txt自定义换行符
- 10大iOS开发者最喜爱的类库