/* * author:wxg */ #include<stdio.h> #include<stdlib.h> #include<string.h> /* * 冒泡排序 */ void bubbleSort(int a[],int n){ int i,j,tmp; for(i=0;i<n-1;i++){ for(j=0;j<n-i-1;j++){ //错误 for(j=0;j<n-i;j++) if(a[j]>a[j+1]){ tmp=a[j]; a[j]=a[j+1]; a[j+1]=tmp; } } } } /* * 直接插入排序 */ void insertSort(int a[],int n){ int i,j; for(i=1;i<n;i++){ int tmp = a[i]; for(j=i;j>0;j--){ //错误 for(j=i;j<0;j--) if(tmp<a[j-1]) a[j]=a[j-1]; else break; } a[j]=tmp; } } /* * 快速排序 */ int partion(int a[],int low,int high){ int key=a[low]; while(low<high){ while((low<high)&&(key<a[high])) high--; a[low]=a[high]; // 错误 a[low++]=a[high--]; while((low<high)&&(key>a[low])) low++; a[high]=a[low]; //错误 a[high--]=a[low++]; } a[low]=key; return low; } void QSort(int a[],int low,int high){ if(low<high){ int pivotloc = partion(a,low,high); QSort(a,low,pivotloc-1); QSort(a,pivotloc+1,high); } } /* * 选择排序 */ void selectSort(int a[],int n){ int i,j,tmp,loc; for(i=0;i<n-1;i++){ tmp = a[0];loc=0; for(j=0;j<n-i;j++){ if(tmp<a[j]){ tmp=a[j];loc=j; } } a[loc]=a[j-1]; // 发生错误 a[loc]=a[j];a[j]=tmp a[j-1]=tmp; } } /* * 二分归并排序 */ void mergeArray(int *a,int s,int m,int t){ int i,j,k; int *b=(int *)malloc((t-s+1)*sizeof(int)); for(i=s,j=m+1,k=0;(i<=m)&&(j<=t);k++){ if(a[i]<a[j]){ b[k]=a[i];i++; } else{ b[k]=a[j];j++; } } for(;i<=m;i++)b[k++]=a[i]; for(;j<=t;j++)b[k++]=a[j]; for(i=s,k=0;i<=t;i++,k++){ //错误 for(i=s;i<=t;i++) a[i]=b[i] a[i]=b[k]; } free(b); } void mergeSort(int a[],int s,int t){ int m; if(s<t){ m=(s+t)/2; mergeSort(a,s,m); mergeSort(a,m+1,t); mergeArray(a,s,m,t); } for(int i=s;i<=t;i++){ printf("%d ",a[i]); } printf("\n"); } int main(){ int a[]={4,2,66,5,90,43,6,7}; int n=sizeof(a)/sizeof(a[0]); // insertSort(a,n); // bubbleSort(a,n); // QSort(a,0,n-1); // selectSort(a,n); mergeSort(a,0,n-1); for(int i=0;i<n;i++){ printf("%d ",a[i]); } printf("\n"); return 0; }
*