升序排序:冒泡排序、插入排序、选择排序

// 冒泡排序,稳定
program BubbleSorter;
var
        t, n, i, j : integer;
        a : array[1 .. 100] of integer;
        noswap : boolean;
begin
        readln(n);
        for i := 1 to n do
                read(a[i]);
        for i := 1 to n do
        begin
                noswap := true;
                for j := 1 to n-i do
                        if a[j] > a[j+1] then
                        begin
                                t := a[j];
                                a[j] := a[j+1];
                                a[j+1] := t;
                                noswap := false;
                        end;
                if (noswap) then break;
        end;
        for i := 1 to n do
                write(a[i], '  ');
        readln;
        readln;
end.


// 插入排序,稳定
program InsertSorter1;
var
        m, n, i, j : integer;
        a : array[1 .. 100] of integer;
begin
        readln(n);
        for i := 1 to n do
                read(a[i]);
        for i := 2 to n do
        begin
                m := a[i];
                for j := i-1 downto 1 do
                        if (a[j] > m) then
                                a[j+1] := a[j]
                        else
                                break;
                if (j = 1) and (a[j] > m) then
                        a[j] := m
                else
                        a[j+1] := m;
        end;
        for i := 1 to n do
                write(a[i], '  ');
        readln;
        readln;
end.


program InsertSorter2;
var
        m, n, i, j : integer;
        a : array[1 .. 100] of integer;
begin
        readln(n);
        for i := 1 to n do
                read(a[i]);
        for i := 2 to n do
        begin
                m := a[i];
                j := i-1;
                while (j > 0) and (a[j] > m) do
                begin
                        a[j+1] := a[j];
                        j := j-1;
                end;
                a[j+1] := m;
        end;
        for i := 1 to n do
                write(a[i], '  ');
        readln;
        readln;
end.


// 选择排序,不稳定
program StraightSelectSorter;
var
        n, i, j, p, t : integer;
        a : array[1 .. 100] of integer;
begin
        readln(n);
        for i := 1 to n do
                read(a[i]);
        for i := 1 to n-1 do
        begin
                p := i;
                for j := i+1 to n do
                        if a[j] < a[p] then
                                p := j;
                t := a[i];
                a[i] := a[p];
                a[p] := t;
        end;
        for i := 1 to n do
                write(a[i], '  ');
        readln;
        readln;
end.
posted @ 2010-01-21 11:26  SmartIOI  阅读(186)  评论(0)    收藏  举报
本站采用CC授权如需转载、引用文章,请务必附上作者及来源处。 Creative Commons License