1.冒泡排序
int a[10] = {4,3,7,6,0,9,8,1,2,5}; int n = 10; for(int i=0;i<n-1;i++){ //趟数 for (int j=0;j<n-i-1;j++){ //对数据进行排序 if(a[j]>a[j+1]){ int t = a[j]; a[j] = a[j+1]; a[j+1] = t; } } }
2.选择排序
int a[10] = {4,3,7,6,0,9,8,1,2,5}; int n = 10; int min = 0; for(int i=0;i<n-1;i++){ min = i; for (int j=i+1;j<n;j++){ if(a[j]<a[min]){ min = j; } } if(min!=i){ int t = a[min]; a[min] = a[i]; a[i] = t; } } for (int m = 0;m<10;m++){ printf("%d",a[m]); }
3.插入排序
int a[10] = {4,3,7,6,0,9,8,1,2,5}; int n = 10; int min = 0; for (int i=1;i<10;i++){ int temp = a[i]; //从第一处开始 for(int j=i;j>0&&a[j-1]>temp;j--){ //向前插入 a[j]=a[j-1]; //元素后移 } a[j] = temp; } for (int m = 0;m<10;m++){ printf("%d",a[m]); }
4.快速排序:
public void quickSort(int arr[],int start,int end){ if(start > end) return; int temp = arr[start]; int i=start; int j= end; while (i!=j){ while (arr[j]>=temp && j>i) j--; while (arr[i]<=temp && j>i) i++; if(j>i){ int t = arr[j]; arr[j]=arr[i]; arr[i]=t; } } arr[start] = arr[i]; arr[i]= temp; quickSort(arr,start,i-1); quickSort(arr,i+1,end); }