经典排序算法总结(代码)

  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

经典排序算法总结(代码)

--fly分享

目录

/*冒泡法 (2)

/*快速排序 (3)

/*插入排序 (4)

/*希尔(shell)排序 (5)

/*选择排序 (6)

/*堆排序 (7)

/*归并排序 (9)

附:

排序算法原理:

/wiki/Category:%E6%8E%92%E5%BA%8F%E7%AE%97%E6% B3%95

flash演示: /kecheng1/site01/suanfayanshi/list.asp?id=7

#include

#include

using namespace std;

/* 冒泡法

左右元素相比,往后冒泡*/

template

void BubbleSort(T* r, int n) {

T temp;

int i,j;

for (i=0;i

{

for (j=0;j

{

if (r[j] > r[j+1])

{

temp = r[j];

r[j] = r[j+1];

r[j+1] = temp;

}

}

}

}

左边比他小,右边比他大,每次得到一个最左边数据的位置*/

template

void QuickSort(T a[],int low,int high)

{

if(low < high)

{

T elem = a[low];

int l = low, r = high;

while(l < r)

{

while(l < r && a[r] >= elem) r--;

if (l < r)

{

a[l++] = a[r];

}

while(l< r && a[l] <= elem) l++;

if (l < r)

{

a[r--] = a[l];

}

}

a[r] = elem;

QuickSort(a,low,r-1);

QuickSort(a,r+1,high);

}

}

向右移,a[j+1]=a[j]*/ template

void insert_sort(T a[],int n)

{

int i,j;

T elem;

for (i= 1;i

{

j = i- 1;

elem = a[i];

while(j>=0 && elem < a[j] )

{

a[j+1] = a[j]; j--;

}

a[j+1] = elem;

}

}

/*希尔(shell)排序

把插入排序的改成d即可*/ template

void shell_insert(T array[],int d,int len) {

int i,j;

T elem;

for ( i = d;i < len;i++)

{

j = i - d;

elem = array[i];

while (j >= 0 && elem < array[j])

{

array[j+d] = array[j];

j = j - d;

}

array[j+d] = elem;

}

}

template

void shell_sort(T array[],int len)

{

int inc = len;

do

{

inc = inc/2;

shell_insert(array,inc,len);

}

while (inc > 1);

}

/*选择排序

逐一比较,最小的放前面*/ template

void SelectSort(T a[],int n) {

int i,j,elemNum;

T elem;

for (i=0;i

{

elemNum = i;

for (j= i+1;j

{

if (a[j] < a[elemNum])

{

elemNum = j;

}

}

if (elemNum != i)

{

elem = a[i];

a[i] = a[elemNum];

a[elemNum] = elem;

}

}

}

/*堆排序

a[s]>=a[2*s] && a[s]>=a[2*s+1]*/ template

void Max_heap(T a[],int S,int len) {

int l = 2*S;

int r = 2*S+1;

int maxI = S;

T elem;

if (l < len && a[l] > a[maxI])

{

maxI = l;

}

if (r < len && a[r] > a[maxI])

{

maxI = r;

}

if (maxI != S)

{

elem = a[S];

a[S] = a[maxI];

a[maxI] = elem;

Max_heap(a,maxI,len);

}

}

template

void HeapSort(T a[],int n)

{

int i;

T elem;

相关文档
最新文档