直接排序
//Direct_Sort //基本不用,不稳 #include<stdio.h> int main() { int num[100], i, n, j, k ,temp; scanf_s("%d\n", &n); for (i = 0; i < n; i++) { scanf_s("%d", &num[i]); } for (int i = 0; i < n; i++) { int minpos = i; for (j = i + 1; j < n; j++) { minpos = num[j] < num[minpos] ? j : minpos; }//比较大小 int temp = num[i]; num[i] = num[minpos]; num[minpos] = temp; }//交换 for (k = 0; k < n; k++) { printf("%d\t", num[k]); } return 0; }
冒泡排序
//Bubble_Sort //基本不用太慢 #include<stdio.h> int main() { int num[100], n, i, j,temper; scanf_s("%d", &n); for (i = 0; i < n; i++) { scanf_s("%d", &num[i]); } for (i = 0; i < n; i++) { for (j = 1; j < n-i; j++) { if (num[j-1] > num[j]) { temper = num[j-1]; num[j-1] = num[j]; num[j] = temper; } } } for (i = 0; i < n; i++) { printf("%d\t", num[i]); } return 0; }
插入排序
//Insertion_Sort //样本小且基本有序的情况下,效率高 #include<stdio.h> int main() { int num[100], i, j, n,temper; scanf_s("%d", &n); for (i = 0; i < n; i++) { scanf_s("%d", &num[i]); } for(i=0;i<n;i++){ for (j = i+1; j >= 1 ; j--) { if (num[j] <= num[j - 1]) { temper = num[j]; num[j] = num[j - 1]; num[j - 1] = temper; } } } for (i = 0; i < n; i++) { printf("%d\t", num[i]); } }
桶排序
#include <stdio.h> int main() { int sort[1001],i,j,t,n; for(i=0;i<=1000;i++){ sort[i]=0; }//初始化数组 scanf("%d",&n); for(i=1;i<=n;i++){ scanf("%d",&t); book[t]++; //读入n个数值 } for(i=1000;i>=0;i--){ for(j=1;j<=book[i];j++){ printf("%d ",i); } } getchar();getchar(); return 0; }
快速排序(常用)
int compare(int*a ,int*b) { return *(int*)a-*(int*)b;//升序 } qsort(arr,arrSize,sizeof(int),compare); //使用stdlib.h文件中的qsort函数进行快速排序 //O(n*log(n))
#include<stdio.h> int a[101], n; void quicksort(int left, int right) { int i, j, t, temp; if (left > right) return; temp = a[left]; i = left; j = right; while (i != j) { while (a[j] >= temp && i < j) j--; while (a[i] <= temp && i < j) i++; if (i < j) { t = a[i]; a[i] = a[j]; a[j] = t; } } a[left] = a[i]; a[i] = temp; quicksort(left, i - 1); quicksort(i + 1, right); } int main() { int i, j, t; scanf_s("%d", &n); for (i = 1; i <= n; i++) { scanf_s("%d", &a[i]); } quicksort(1, n);//调用快速排序 for (i = 1; i <= n; i++) { printf("%d", a[i]); } getchar(); getchar(); return 0; }//按大小打印出来 //快速排序