排序算法--插入、快排、选择、冒泡、堆排序、归并

1.插入排序:

procedure in_sort(var a: array of Integer; k, m: Integer);
var
p: Integer;
begin
p :
= 0;
while p = 0 do
begin
if k >= a[m] then
begin
a[m
+ 1] := k;
p :
= 1;
end
else
begin
a[m
+ 1] := a[m];
Dec(m);
if m = -1 then
begin
a[m
+ 1] := k;
p :
= 1;
end;
end;
end;
end;

2.快速排序:

procedure q_sort(var a: array of Integer; l, r: Integer);
var
i, j, mid, t: Integer;
begin
i :
= l;
j :
= r;
mid :
= a[(l + r) div 2];
while i <= j do
begin
while (a[i] < mid) do
Inc(i);
while (a[j] > mid) do
Dec(j);
if i <= j then
begin
t :
= a[i];
a[i] :
= a[j];
a[j] :
= t;
Inc(i);
Dec(j);
end;
end;
if l < j then
q_sort(a, l, j);
if i < r then
q_sort(a, i, r);
end;

3.选择排序:

procedure sel_sort(var a: array of Integer; l, r: Integer);
var
i, j, k, t: Integer;
begin
for i := l to r do
begin
k :
= i;
for j := i + 1 to r do
begin
if a[j] < a[k] then
k :
= j;
end;
if k <> i then
begin
t :
= a[k];
a[k] :
= a[i];
a[i] :
= t;
end;
end;
end;

4.冒泡排序:

procedure b_sort(var a: array of Integer; l, r: Integer);
//l,r表示上下标
var
i, j, t: Integer;
begin
for i := l to r do
for j := l to i - 1 do
begin
if a[j] > a[i] then
begin
t :
= a[i];
a[i] :
= a[j];
a[j] :
= t;
end;
end;
end;

5.堆排序:

procedure heap_adjust(var a: array of Integer; i, m: Integer);
var
k, t: Integer;
begin
t :
= a[i];
k :
= i * 2;
while k <= m do
begin
if (a[k] < a[k + 1]) and (k < m) then
Inc(k);
if (t < a[k]) then
begin
a[i] :
= a[k];
i :
= k;
k :
= 2 * i; //调整,并为t在下面节点找位置
//k向下探索
end
else
k :
= m + 1;
end;
a[i] :
= t;
end;
procedure he_sort(var a: array of Integer; l, r: Integer);
var
j, t: Integer;
begin
for j := r div 2 to l do
heap_adjust(a, j, r);
//调整堆,初始化
for j := r downto l do
begin
t :
= a[0];
a[
0] := a[j];
a[j] :
= t;
heap_adjust(a, l, j
- 1);
end;
end;

6.归并排序:

procedure merge(var a: array of Integer; l, q, r: Integer);
{将已排序好的子序列a[l..p]与a[q+1..r]合并为有序的tmp[l..r]}
var
i, j, t: Integer;
tmp:
array[0..20] of Integer;
begin
i :
= l;
j :
= q + 1;
t :
= l;
while t <= r do
begin
if ((i <= q) and (a[i] <= a[j])) or (j > r) then
begin
tmp[t] :
= a[i];
Inc(i);
end
else
begin
tmp[t] :
= a[j];
Inc(j);
end;
Inc(t);
end;
for t := l to r do
a[t] :
= tmp[t];
end;
procedure me_sort(var a: array of Integer; l, r: Integer);
var
q: Integer;
begin
if l <> r then
begin
q :
= (l + r) div 2;
me_sort(a, l, q);
me_sort(a, q
+ 1, r);
merge(a, l, q, r);
end;
end;

 

  

posted @ 2011-08-25 15:29  wouldguan  阅读(216)  评论(0编辑  收藏  举报