您的位置:首页 > 运维架构 > Shell

内排序(插入排序、冒泡排序、选择排序、shell排序、快速排序、归并排序、堆排序)

2012-03-06 17:27 573 查看
插入排序:逐个处理待排序的记录。每个新纪录与前面已排序的子序列进行比较,将它插入到子序列中正确的位置。

template <typename E, typename Comp>

void inssort(E A[], int n) { // Insertion Sort

for (int i=1; i<n; i++) // Insert i'th recor

for (int j=i; (j>0) && (Comp::prior(A[j], A[j-1])); j--)

swap(A, j, j-1);}

冒泡排序:包括一个简单的双重for循环。第一次的内部for循环从记录数组的底部比较到顶部,比较相邻的关键码。如果低序号的关键码值比高序号的关键码值大,则将二者交换顺序。一旦遇到一个最小关键码值,这个过程将是他像气泡一样被推到数组的顶部,第二次再重复上面的过程。但是,既然知道最小元素被排到了数组的最前面,没有必要在比较最上面的两个元素了。同样,每一轮循环都是比较相邻的关键码,但是都将比上一轮循环少比较一个关键码。

template <typename E, typename Comp>

void bubsort(E A[], int n) { // Bubble Sort

for (int i=0; i<n-1; i++) // Bubble up i'th record

for (int j=n-1; j>i; j--)

if (Comp::prior(A[j], A[j-1]))

swap(A, j, j-1);}

选择排序:选择排序的第i次是选择数组中第i小的记录,并将该记录放到数组的第i个位置。

template<class elem,class comp>

void selsort(elem A[],int n){

for(int i=0;i<n-1;i++){

int lowindex=i;

for(int j=n-1;j>i;j--)

if(comp::lt(A[j],A[lowindex]))

lowindex=j;

swap(A,i,lowindex);

}}

shell排序:使用分组并排序的,将序列分成子序列,然后分别对子序列进行排序,最后将子序列组合起来。将数组元素分成虚拟子序列,每个子序列用插入排序方法进行排序。

template<class elem,class comp>

void inssort2(elem A[],int n,int incr){

for (int i=incr;i<n;i+=incr)

for(int j>=i;(j>=incr)&&( comp:: lt (A[ j ],A[ j -incr ])); j-=incr)

swap( A, j ,j-incr);

}

template<class elem,class comp>

void shellsort(elem A[],int n){

for(int i=n/2;i>2;i/=2){

for(int j=0;j<i;j++)

inssort2< elem ,comp>( &A[ j ],n-j; i);

inssort2< elem ,comp>( A , n ; 1 ); }

快速排序:首先选择一个轴值,假设输入的数组中有k个小于轴值的结点,于是这些节点被放在数组最左边的k个位置上,而大于轴值的结点被放在数组最右边的n-k个位置上。在给定分割中的值不必排序,只要求所有节点都放在了正确的位置上,而轴值的位置就是下标k。快速排序再对轴值的左右子数组分别进行类似的操作,其中一个数组有k个元素,另一个数组有n-k-1个元素。

template<class elem,class comp>

void qsort(elem A[],int i,int j){

// Simple findpivot: Pick middle value in array

template <typename E>

inline int findpivot(E A[], int i, int j)

{ return (i+j)/2; }

// Partition the array

template <typename E, typename Comp>

inline int partition(E A[], int l, int r, E& pivot) {

do { // Move the bounds inward until they meet

while (Comp::prior(A[++l], pivot)); // Move l right and

while ((l < r) && Comp::prior(pivot, A[--r])); // r left

swap(A, l, r); // Swap out-of-place values

} while (l < r); // Stop when they cross

return l; // Return first position in right partition

}

// qsort core function: Basic qsort

template <typename E, typename Comp>

void qsort(E A[], int i, int j) { // Quicksort

if (j <= i) return; // Don't sort 0 or 1 element

int pivotindex = findpivot(A, i, j);

swap(A, pivotindex, j); // Put pivot at end

// k will be the first position in the right subarray

int k = partition<E,Comp>(A, i-1, j, A[j]);

swap(A, k, j); // Put pivot in place

qsort<E,Comp>(A, i, k-1);

qsort<E,Comp>(A, k+1, j);

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐