//快速排序 //冒泡排序 快速排序 #include<stdio.h> #include<stdlib.h> void swap(int *a,int i,int j) { int t; t=a[i]; a[i]=a[j]; a[j]=t; } void bublesort(int *a,int n) { int i,j,t; for(i=1;i<n;i++) { for(j=1;j<=n-i;j++) { if(a[j+1]<a[j]) swap(a,j,j+1); } } } int Partition(int *a,int low,int high) { int t=a[low]; while(low<high) { while(low<high&&a[high]>t) high--; a[low]=a[high]; while(low<high&&a[low]<t) low++; a[high]=a[low]; } a[low]=t; return low; } void quicksort(int *a,int low,int high) { int m; if(low<high) { m=Partition(a,low,high); quicksort(a,low,m-1); quicksort(a,m+1,high); } } void output(int *a,int n) { int i; for(i=1;i<=n;i++) printf("%d ",a[i]); printf("/n"); } int main() { int a[]={0,12,78,895,24,158,369,58,621,1475,2}; output(a,10); quicksort(a,1,10); output(a,10); system("pause"); } #include<stdio.h> #include<stdlib.h> void swap(int *a,int i,int j) { int t; t=a[i]; a[i]=a[j]; a[j]=t; } void merge(int *a1,int a1_start,int *a2,int a2_start,int a2_end,int *a3,int a3_start,int a3_end) //2-路插入的合并 { int b[100]; int i,j,k; i=a2_start; j=a3_start; k=0; while(i<=a2_end&&j<=a3_end) { if(a2[i]<a3[j]) b[k++]=a2[i++]; else b[k++]=a3[j++]; } while(i<=a2_end) b[k++]=a2[i++]; while(j<=a3_end) b[k++]=a3[j++]; for(i=0;i<k;i++) a1[a1_start+i]=b[i]; } void mergesort(int *a,int start,int end) // 2-路插入排序 { int m; if(start<end) { m=(start+end)/2; mergesort(a,start,m); mergesort(a,m+1,end); merge(a,start,a,start,m,a,m+1,end); } } int main() { int a[]={0,12,78,895,24,158,369,58,621,1475,2}; output(a,10); mergesort(a,10); output(a,10); system("pause"); } //选择排序 堆排序 #include<stdio.h> #include<stdlib.h> void heapcreate(int *a,int l,int h) { int i,j,t; i=l; j=2*l; t=a[i]; while(j<=h) { if(j<h&&a[j]<a[j+1])j++; if(t<a[j]) { a[i]=a[j]; i=j; j=2*i; } else j=h+1; } a[i]=t; } void heapsort(int *a,int n) { int i,j,k; for(i=n/2;i>0;i--) heapcreate(a,i,n); for(i=n;i>1;i--) { k=a[i]; a[i]=a[1]; a[1]=k; heapcreate(a,1,i-1); } } void output(int *a,int n) { int i; for(i=1;i<=n;i++) printf("%d ",a[i]); printf("/n"); } int main() { int a[]={0,12,78,895,24,158,369,58,621,1475,2}; output(a,10); heapsort(a,10); output(a,10); system("pause"); }