[size=14.285715103149414px]1.冒泡算法 [size=14.285715103149414px] #include ''stdio.h' [size=14.285715103149414px]void main() [size=14.285715103149414px]{ [size=14.285715103149414px]int a[10]={82,12,4,56,100.....} [size=14.285715103149414px]n=10; [size=14.285715103149414px]for(i=0;i<n-1;i++) // 代表第几次循环 [size=14.285715103149414px] for(j=0;j<n-1-i;j++) // 代表这一次要比较大小多少回 [size=14.285715103149414px] if(a[j]>a[j+1]) //当后面的值比前面的值小时,两个值互换 [size=14.285715103149414px] { t=a[j]; [size=14.285715103149414px] a[j]=a[j+1]; [size=14.285715103149414px] a[j+1]=t; [size=14.285715103149414px]} [size=14.285715103149414px]for(i=0;i<n;i++) // 输出排序后的数组a; [size=14.285715103149414px]printf("%d ",a ); [size=14.285715103149414px]} [size=14.285715103149414px]
[size=14.285715103149414px]
[size=14.285715103149414px]2.选择排序法 [size=14.285715103149414px]#include <stdio.h> [size=14.285715103149414px]#define N 20 //定义N=20 [size=14.285715103149414px]void main() [size=14.285715103149414px]{ [size=14.285715103149414px]int a[N],i,j,p,t; [size=14.285715103149414px]for(i=0;i<N;i++) [size=14.285715103149414px] scanf("%d",&a); //得到a[N]数组 [size=14.285715103149414px] for(i=0;i<N-1;i++) //从a[0]开始比较 [size=14.285715103149414px] { p=i; [size=14.285715103149414px] for(j=i+1;j<N;j++) //如果后面的数值比前面的数值大的话,就交换数组中的值,否则不交换。进入下个循环。 [size=14.285715103149414px] if(a[j]<a[p]) [size=14.285715103149414px] p=j; [size=14.285715103149414px] if(p!=i) [size=14.285715103149414px] { t=a[p]; [size=14.285715103149414px] a[p]=a; [size=14.285715103149414px] a=t; [size=14.285715103149414px] } [size=14.285715103149414px] } [size=14.285715103149414px]for(i=0;i<N;i++) //输出排序好的数组 [size=14.285715103149414px]printf("%d ",a); [size=14.285715103149414px]printf("\n"); [size=14.285715103149414px]} [size=14.285715103149414px]
[size=14.285715103149414px]
[size=14.285715103149414px]3.插入法
[size=14.285715103149414px]#include <stdio.h> //这是降序插入排序法,个人感觉跟冒泡法近似 [size=14.285715103149414px]main() [size=14.285715103149414px]{ [size=14.285715103149414px]int a[10],i,j,t; [size=14.285715103149414px]for(i=0;i<10;i++) [size=14.285715103149414px]scanf("%d",&a); // 一样的 先得到数组a; [size=14.285715103149414px]for(i=1;i<10;i++) [size=14.285715103149414px]{ [size=14.285715103149414px]t=a; //先把要插入的数据存入变量t中; [size=14.285715103149414px]for( j=i-1 ; j>=0 && t>a[j] ; j-- ) //然后从a[1]开始与前面的数组比较大小,当满足条件时交换数组中的值 [size=14.285715103149414px]a[j+1]=a[j]; [size=14.285715103149414px]a[j+1]=t; // 比较完成,把变量t中的值插入空余的数组中。 [size=14.285715103149414px]} [size=14.285715103149414px]for(i=0;i<10;i++) //排序输出数组 [size=14.285715103149414px]printf("%d ",a); [size=14.285715103149414px]printf("\n"); [size=14.285715103149414px]} [size=14.285715103149414px]上面三个排序方法。冒泡法最好理解,但运行时处理过程较多。排序较慢。 |