C语言 - 直接插入排序和直接选择排序算法

1、直接插入排序
 1 #include<stdio.h>
 2 
 3 struct node
 4 {
 5     int key;
 6 };
 7 typedef struct node DataType;
 8 
 9 int Ins_Sort(DataType Ar[],int n);
10 
11 int main(void)
12 {
13 
14     int n,i;
15     DataType array[20];
16 
17     printf("Input the length of the array <<20>:");
18     scanf("%d",&n);
19     for(i=0; i<n; i++)                 //输入数组
20     {
21         printf("Input %d datas:",i+1);
22         scanf("%d",&array[i]);
23     }
24 
25     printf("\n The array are:");
26     for(i=0; i<n; i++)
27     {
28         printf("%4d",array[i]);              //输入的数组显示
29     }
30 
31     Ins_Sort(array, n);
32 
33     printf("\n The array after Ins_Sort are:");
34     for(i=0; i<n; i++)             //输出排序后的算法结果
35     {
36         printf("%4d",array[i]);
37     }
38     return(0);
39 }
40 
41 
42 int Ins_Sort(DataType Ar[],int n)       //直接插入排序算法
43 {
44     int i,j;
45     DataType temp;
46     for(i=1;i<n;i++)            //总共要进行n-1扫描
47     {
48         temp=Ar[i];         //每次扫描总是把被考察排序码存入临时单元
49         j=i-1;              //j规定了这次比较范围的上界
50         while((temp.key<Ar[j].key)&&(j>=0))
51         {
52             Ar[j+1]=Ar[j];
53             j--;
54         }
55         Ar[j+1]=temp;    //完成插入
56     }
57 }
2、直接选择排序算法
 1 #include<stdio.h>
 2 
 3 struct node
 4 {
 5     int key;
 6 };
 7 typedef struct node DataType;      //DataType是struct node的别名
 8 
 9 int Sel_sort(DataType Ar[],int n);      //声明直接选择排序算法
10 
11 int main(void)
12 {
13 
14     int n,i;
15     DataType array[20];
16 
17     printf("Input the length of the array <<20>:");
18     scanf("%d",&n);
19     for(i=0; i<n; i++)                 //输入数组
20     {
21         printf("Input %d datas:",i+1);
22         scanf("%d",&array[i]);
23     }
24 
25     printf("\n The array are:");
26     for(i=0; i<n; i++)
27     {
28         printf("%4d",array[i]);              //输入的数组显示
29     }
30 
31     Sel_sort(array,n);          //调用排序算法
32     printf("\n The array after Sel_sort are:");
33     for(i=0; i<n; i++)             //输出排序后的算法结果
34     {
35         printf("%4d",array[i]);
36     }
37     return(0);
38 }
39 
40 int Sel_sort(DataType Ar[],int n)          //直接选择排序算法
41 {
42     DataType temp;
43     int i,small,j;
44     for(i=0; i<=n-1; i++)             //i控制n-1趟扫描
45     {
46         small=i;                        //用变量small记住当前最小排序码的位置
47         for(j=i+1; j<n; j++)            //j控制这趟扫描的比较范围
48             if(Ar[j].key<Ar[small].key)      //如果发现更小者,随时修改small的值
49                 small=j;
50         if(small!=i)                               //small与比较范围首元素下标不同,则交换
51         {
52             temp=Ar[i];                 //交换是利用临时变量temp进行的
53             Ar[i]=Ar[small];
54             Ar[small]=temp;
55         }
56     }
57 }
58 //直接选择排序的效率与初始状态无关,即无最好最坏的情况.时间复杂度为O(n*n),不是稳定的排序算法

 

posted @ 2015-10-27 20:29  默默笙萧  阅读(10066)  评论(0编辑  收藏  举报