排序算法--排序算法汇总(一)

2014-11-24 08:18:50 · 作者: · 浏览: 2
排序算法无疑是学习数据结构中的重点内容,本文将给出排序算法的汇总。
下面是具体的实现:
[cpp]
#include
#include
#include
#define N 1000000
int Array[N];
int Temp[N];
//1、冒泡排序
void BubbleSort(int a[],int n){
int i,j;
int temp;
int tag;
for(i=n-1;i>0;i--){
tag = 0;
for(j=0;j
if(a[j]>a[j+1]){
temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
tag=1;
}
if(tag==0) break;
}
}
//2、简单插入排序
void SimpleInsertSort(int a[],int n){
int i,j,k;
int temp;
for(i=1;i
for(j=0;j
if(a[j]>a[i]){
k=j;
break;
}
if(j==i) continue;
temp=a[i];
for(j=i;j>k;j--)
a[j]=a[j-1];
a[k]=temp;
}
}
//3、希尔排序
void ShellSort(int a[],int n,int d){
int h,i,j,k;
int temp;
do{
d=d/3+1;
for(h=0;h
for(i=h+d;i
for(j=h;j
if(a[j]>a[i]){
k=j;
break;
}
if(j==i) continue;
temp=a[i];
for(j=i;j>k;j-=d)
a[j]=a[j-d];
a[k]=temp;
}
}while(d>1);
}
//4、简单选择排序
void SimpleSelectSort(int a[],int n){
int i,j,k;
int temp;
for(i=0;i
temp=a[i];
k=i;
for(j=i+1;j
if(a[j]
temp=a[j];
k=j;
}
if(k!=i){
temp=a[i];
a[i]=a[k];
a[k]=temp;
}
}
}
//5、堆排序
void CreateHeap(int a[],int n){
int i,j;
int temp;
for(i=(n-2)/2;i>=0;i--){
j=2*i+1;
while(j
if(j+1a[j])
j++;
if(a[(j-1)/2]
temp=a[(j-1)/2];
a[(j-1)/2]=a[j];
a[j]=temp;
}
else break;
j=2*j+1;
}
}
}
void HeapAdjust(int a[],int n){
int i=0;
int j;
int temp;
while(i
j=2*i+1;
if(j+1a[j])
j++;
if(a[i]
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
else break;
i=j;
}
}
void HeapSort(int a[],int n){
int i;
int temp;
CreateHeap(a,n);
for(i=n-1;i>0;i--){
temp=a[i];
a[i]=a[0];
a[0]=temp;
HeapAdjust(a,i);
}
}
//6、快速排序
int partition(int a[],int low,int high){
int pivotKey=a[low];
while(low
while(low
high--;
a[low]=a[high];
while(low
low++;
a[high]=a[low];
}
a[low]=pivotKey;
return low;
}
void QuickSort(int a[],int low,int high){
int pivotTag;
if(low
pivotTag=partition(a,low,high);
QuickSort(a,low,pivotTag-1);
QuickSort(a,pivotTag+1,high);
}
}
//7、归并排序
void Merge(int a[],int p,int q,int r){
int i,j;
int *ptr=(int*)malloc((r-p+1)*sizeof(int));
int begin_1,