1.冒泡排序
void bubble_sort(int s[],int n){
int i,j;
for(i=n-1;i>0;i--){
for(j=0;j<i;j++){
if(s[j]<s[j+1])swap(s[j],s[j+1]);
}
}
}
2.插入排序
void insertion_sort(int s[],int n){
int t,i,j;
for(i=1;i<n;i++){
if(s[i]<s[i-1]){
t=s[i];s[i]=s[i-1];
j=i-2;
while(t<s[j]&&j>=0){
s[j+1]=s[j];
j--;
}
s[j+1] = t;
}
}
}
3.选择排序
void swap(int a,int b){
int t=a;
a=b;
b=t;
}
void selection_sort(int s[],int n){
int i,j,mi,mj;
for(i=0;i<n-1;i++){
mi=INT_MAX;
for(j=i;j<n;j++){
if(s[j]<mi){
mi=s[j];
mj=j;
}
}
if(i!=mj)swap(s[i],s[mj]);
}
}
4.快速排序
#include<cstdlib>
int cmp(const void *a ,const void *b){
return *(int *)a-*(int *)b;
}
qsort(a,1000,sizeof(int),cmp);
void swap(int a,int b){
int t=a;
a=b;
b=t;
}
void quick_sort(int s[],int l,int r){
if(l<r){
int t=s[(l+r)/2];
int i=l,j=r;
while(i<j){
while(s[i]<t)i++;
while(s[j]>t)j--;
if(i<=j){
swap(s[i],s[j]);
i++;
j--;
}
}
quick_sort(s,l,j);
quick_sort(s,i,r);
}
}
void swap(int a,int b){
int t=a;
a=b;
b=t;
}
void quick_sort(int s[],int l,int r){
int i=l,j=r,t=s[(l+r)/2];
while(i<j){
while(i<=r&&s[i]<=t)i++;
while(j>=0&&s[j]>=t)j--;
if(i<j&&i<=r&&j>=0){
swap(s[i],s[j]);
i++;
j--;
}
}
if(i<r)quick_sort(s,i,r);
if(j>l)quick_sort(s,l,j);
}
5.堆排序
来源
void HeapAdjust(int i,int size){
int r,l;
r=2*i+1;
l=2*i;
p=i;
if(i<=size/2){
if(a[p]<a[r]&&r<=size)p=r;
if(a[p]<a[l]&&l<=size)p=l;
if(p!=i){
t=a[p];
a[p]=a[i];
a[i]=t;
HeapAdjust(p,size);
}
}
}
void BuildHeap(int size){
int i;
for(i=size/2;i>=1;i--)HeapAdjust(i,size);
}
void HeapSort(int size){
int i,t;
BuildHeap(size);
for(i=size;i>1;i--){
t=a[1];
a[1]=a[i];
a[i]=t;
HeapAdjust(1,i-1);
}
}
6.归并排序
来源
void mergearray(int a[],int first,int mid,int last,int temp[]){
int i=first,j=mid+1;
int m=mid,n=last;
int k=0;
while(i<=m&&j<=n){
if(a[i]<=a[j])temp[k++]=a[i++];
else temp[k++]=a[j++];
}
while(i<=m)temp[k++]=a[i++];
while(j<=n)temp[k++]=a[j++];
for(i=0;i<k;i++)a[first+i]=temp[i];
}
void mergesort(int a[],int first,int last,int temp[]){
if (first<last){
int mid=(first+last)/2;
mergesort(a,first,mid,temp);//左边有序
mergesort(a,mid+1,last,temp);//右边有序
mergearray(a,first,mid,last,temp);//再将二个有序数列合并
}
}
bool MergeSort(int a[],int n){
int *p=new int[n];
if(p==NULL)return false;
mergesort(a,0,n-1,p);
delete[] p;
return true;
}