1.冒泡排序法:
1 //方法1--从小到大(假设有数组int array[n])
2 void bubbleSort(int *array,int n)
3 {
4 int tmp;
5 for(int i=0;i<n-1;i++) {
6 for(int j=0;j<n-1-i;j++) {
7 if(array[j]>array[j+1]) {
8 tmp=array[j];
9 arrar[j]=array[j+1];
10 array[j+1]=tmp;
11 }
12 }
13 }
14 }
1 //方法2--从大到小
2 void bubbleSort(int *array,int n)
3 {
4 int tmp;
5 for(int i=0;i<n;i++) {
6 for(int j=n-1;j>i;j--) {
7 if(array[j]>array[j-1]) {
8 tmp=array[j];
9 array[j]=array[j-1];
10 array[j-1]=tmp;
11 }
12 }
13 }
14 }
2.交换排序法:
1 void changeSort(int *array,int n)
2 {
3 int tmp;
4 for(int i=0;i<n-1;i++)
5 for(int j=i+1;j<n;j++)
6 if(array[i]>array[j]) {
7 tmp=array[i];
8 array[i]=array[j];
9 array[j]=tmp;
10 }
11 }
12 }
13 }
3.选择排序法
1 void selectSort(int *array,int n)
2 {
3 int tmp,ipos;
4 for(int i=0;i<n-1;i++) {
5 tmp=array[i];
6 ipos=i;
7 for(int j=0;j<n;j++) {
8 if(tmp>array[j]) {
9 tmp=array[j];
10 ipos=j;
11 }
12 array[ipos]=array[i];
13 array[i]=tmp;
14 }
15 }
4.插入排序法
1 //方法1--从小到大
2 void insertSort(int *array,int n)
3 {
4 int tmp;
5 for(int i=1;i<n-1;i++) {
6 tmp=array[i];
7 for(int j=i-1;j>=0;j--) {
8 if(tmp<array[j]) {
9 array[j+1]=array[j];
10 }//块移位,空出需要插入的位置
11 else
12 break;
13 }
14 array[j+1]=tmp;
15 }
16 }
17
18 //方法2--从大到小
19 void insertSort(int *array,int n)
20 {
21 int tmp,j;
22 for(int i=1;i<n;i++) {
23 tmp=array[i];
24 j=i;
25 while(j>0&&tmp>array[j-1]) {
26 array[j]=array[j-1];
27 j--;
28 }
29 array[j]=tmp;
30 }
31 }