【本课例子】
(1)快速排序:分割算法
① 快速排序程序:
QUICKSORT( A, p, r )
if p < r
q = PARTITION( A, p, r )
QUICKSORT( A, p, q - 1 )
QUICKSORT( A, q + 1, r )
② 数组划分
PARTITION( A, p, r )
x = A[r]
i = p - 1
for j = p to r - 1
if a[j] < x
i += 1
exchange A[i] with A[j]
exchange A[i+1] with A[r]
return i + 1
(2)随机算法
① 新的划分程序中,仅在真正进行划分前进行一次交换:
RANDOMIZED-PARTITION( A, p, r )
i = RANDOM( p, r )
exchange A[r] with A[i]
return PARTITION( A, p, r )
② 新的快速排序不再调用PARTITION,而是调用RANDOMIZED-PARTITION:
RANDOMIZED-QUICKSORT( A, p, r )
if p < r
q = RANDOMIZED-PARTITION( A, p, r )
RANDOMIZED-QUICKSORT( A, p, q - 1 )
RANDOMIZED-QUICKSORT( A, q + 1, r )
#if 0
【本课例子】
(1)快速排序:分割算法
(2)随机算法
#endif
#if 1
#include <iostream>
#include <queue>
using namespace std;
struct LOC{
int low;
int high;
LOC& operator=( LOC& rhs ){
this->low = rhs.low;
this->high = rhs.high;
return *this;
}
};
int partion( int a[], int low, int high );
void quick_sort( int a[], int low, int high );
int main( void )
{
cout << "2014-6-4 16:06:57" << endl;
int a[] = { 13, -3, -25, 20, -3, -16, -23, 18, 20, -7, 12, -5, -22, 15, -4, 7 };
partion( a, 0, sizeof( a ) / sizeof( int ) - 1 );
for( int i = 0; i < sizeof( a ) / sizeof( int ); ++i )
cout << a[i] << " ";
cout << endl;
quick_sort( a, 0, sizeof( a ) / sizeof( int ) - 1 );
for( int i = 0; i < sizeof( a ) / sizeof( int ); ++i )
cout << a[i] << " ";
cout << endl;
//int *b = NULL;
//quick_sort( b, 0, sizeof( b ) / sizeof( int ) - 1 );
return 0;
}
int partion( int a[], int low, int high )
{
int pivot = a[low];
while( low < high ){
while( low < high ){
if( a[high] < pivot )
break;
--high;
}
if( low < high )
a[low] = a[high];
while( low < high ){
if( a[low] > pivot )
break;
++low;
}
if( low < high )
a[high] = a[low];
}
a[low] = pivot;
return low;
}
void quick_sort( int a[], int low, int high )
{
if( a == NULL || low >= high )
return;
queue<LOC> qu;
LOC loc, locIn;
loc.low = low;
loc.high = high;
qu.push( loc );
while( !qu.empty() ){
loc = qu.front();
qu.pop();
int mid = partion( a, loc.low, loc.high );
if( loc.low < mid - 1 ){
locIn.low = loc.low;
locIn.high = mid - 1;
qu.push( locIn );
}
if( loc.high > mid + 1 ){
locIn.low = mid + 1;
locIn.high = loc.high;
qu.push( locIn );
}
}
}
#endif
算法执行实例:
算法 | 最坏情况运行时间 | 平均情况/期望运行时间 |
插入排序 | O(n^2) | O(n^2) |
冒泡排序 | O(n^2) | O(n^2) |
选择排序 | O(n^2) | O(n^2) |
归并排序 | O(nlogn) | O(nlogn) |
快速排序 | O(n^2) | O(nlogn) |
堆排序 | O(nlogn) | O(nlogn) |
计数排序 | O(n+k) | O(n+k) |
基数排序 桶排序 | O(d(n+k)) O(n^2) | O(d(n+k)) O(n) |