heshao2005 发表于 2017-7-4 21:36:56

排序

1 /*1)    请编写插入排序程序。
2 2)    请编写选择排序程序。
3 3)    请编写冒泡排序程序。*/
4
5 #include<stdio.h>
6 #include<stdlib.h>
7
8 #defineswap(a,b,c)(c = a,a = b,b=c)
9 void insert(int *p,int N);
10
11 void choose(int *p,int N);
12
13 void buble(int *p,int N);
14
15 void quick (int *p,int left,int right);
16
17 void shuchu(int *p,int N);
18
19 int main()
20 {
21   int N;
22   int i;
23   int *p;
24   scanf("%d",&N);
25
26   
27   p =(int *) malloc(sizeof(int )*N);
28   for(i = 0;i<N;i++)
29         scanf("%d",p+i);
30
31
32   insert(p,N);
33
34   shuchu(p,N);
35
36   choose(p,N);
37
38   shuchu(p,N);
39
40   buble(p,N);
41
42   shuchu(p,N);
43
44   quick(p,0,N-1);
45
46   shuchu(p,N);
47   return 0;
48 }
49
50 void insert(int *p,int N)
51 {
52   int i,j;
53
54   int t;
55
56
57   for(i = 0;i<N;i++)
58   {   
59         int min = 1000;
60         int leap = -1;
61
62         for(j = i;j<N;j++)
63         {
64             if(p<min)
65             {
66               leap = j;
67               min = p;
68             }
69         }
70         swap(p,p,t);
71   }
72 }
73 void choose(int *p,int N)
74 {
75   int i,j;
76   int leap ;
77
78   for(i = 2;i<N;i++)
79   {
80         if(p<p)
81         {
82         leap = p;
83         for(j = i-1;j>0&&leap<p;j--)
84         {
85             if(leap<p)
86             {
87               p=p;
88             }
89         }
90         p = leap;
91         }
92   }
93 }
94
95
96 void buble(int *p,int N)
97 {
98   int i,j;
99   int leap;
100   int exchange = 1;
101
102   for(i = 0;i<N-1&&exchange==1;i++)
103   {
104         for(j = 0;j<N-i-1;j++)
105         {
106             if(p>p)
107             {
108               swap(p,p,leap);
109               exchange = 0;
110             }
111         }
112   }
113 }
114
115 void quick(int *p,int left,int right)
116 {
117   int i,j;
118   int n;
119   int leap;
120   if(left>right)
121         return ;
122
123   i = left;
124   j = right;
125   leap = p;
126   while(i<j)
127   {
128         while(i<j&&p>=leap)
129             j--;
130         while(i<j&&p<=leap)
131             i++;
132         if(i!=j)
133             swap(p,p,n);
134   }
135   swap(p,leap,n);
136
137   quick(p,left,i-1);
138   quick(p,j+1,right);
139 }
140
141 void shuchu(int *p,int N)
142 {
143   int i;
144   for(i = 0;i<N;i++)
145         printf("%4d",p);
146   printf("\n");
147 }
页: [1]
查看完整版本: 排序