几种常见排序
以下是几种常见排序:
1 const max=100;n=10;
2 var i:integer;
3 a,b:array[1..n] of integer;
4 procedure swap(var a,b:integer);
5 var t:integer;
6 begin
7 t:=a;a:=b;b:=t;
8 end;
9 procedure print;
10 var i:integer;
11 begin
12 for i:=1 to n do
13 write(a[i],' ');
14 writeln;
15 end;
16 procedure createArray;
17 var i:integer;
18 begin
19 randomize;
20 for i:=1 to n do
21 a[i]:=random(max);
22 b:=a;
23 writeln('this is the original data:');
24 print;
25 end;
26 procedure insertionSort;
27 var i,j,key:integer;
28 begin
29 for j:=2 to n do
30 begina
31 key:=a[j];
32 i:=j-1;
33 while (i>0) and (a[i]>key) do
34 begin
35 a[i+1]:=a[i];
36 dec(i);
37 end;
38 a[i+1]:=key;
39 end;
40 print;
41 end;
42 procedure bubbleSort;
43 var i,j:integer;
44 begin
45 a:=b;
46 for i:=1 to n-1 do
47 begin
48 for j:=1 to n-i do
49 if a[j]>a[j+1] then swap(a[j],a[j+1]);
50 end;
51 print;
52 end;
53 procedure selectionSort;
54 var i,j,k:integer;
55 begin
56 a:=b;
57 for i:=1 to n-1 do
58 begin
59 k:=i;
60 for j:=i+1 to n do
61 if a[k]>a[j] then k:=j;
62 if k<>i then swap(a[i],a[k]);
63 end;
64 print;
65 end;
66 procedure quickSort(l,r:integer);
67 var i,j,m:integer;
68 begin
69 i:=l;j:=r;m:=a[i];
70 repeat
71 while a[i]<m do inc(i);
72 while a[j]>m do dec(j);
73 if i<=j then
74 begin
75 swap(a[i],a[j]);
76 inc(i);dec(j);
77 end;
78 until i>j;
79 if j>l then quickSort(l,j);
80 if i<r then quickSort(i,r);
81 end;
82 procedure merge(p,q,r:integer);
83 var i,j,k:integer;
84 la,ra:array[1..n+1] of integer;
85 begin
86 j:=1;
87 for i:=p to q do
88 begin
89 la[j]:=a[i];
90 inc(j);
91 end;
92 la[j]:=max;
93 j:=1;
94 for i:=q+1 to r do
95 begin
96 ra[j]:=a[i];
97 inc(j);
98 end;
99 ra[j]:=max;
100 j:=1;i:=1;
101 for k:=p to r do
102 if la[i]<=ra[j] then
103 begin
104 a[k]:=la[i];
105 inc(i);
106 end
107 else
108 begin
109 a[k]:=ra[j];
110 inc(j);
111 end;
112 end;
113 procedure mergeSort(l,r:integer);
114 var i:integer;
115 begin
116 if l<r then
117 begin
118 i:=(r-l) div 2;
119 mergeSort(l,l+i);
120 mergeSort(l+i+1,r);
121 merge(l,l+i,r);
122 end;
123 end;
124 begin
125 createArray;
126 writeln('this is insertionSort:');
127 insertionSort;
128 writeln('this is bubbleSort:');
129 bubbleSort;
130 writeln('this is selectionSort:');
131 selectionSort;
132 a:=b;
133 writeln('this is quickSort:');
134 quickSort(1,n);
135 print;
136 a:=b;
137 writeln('this is mergeSort:');
138 mergeSort(1,n);
139 print;
140
141 end.