Содержание

Сортировка пузырьком

<flashplayer width=320 height=260>file=http://wiki.nsunc.com/_media/sorting/bubble-sort.flv</flashplayer>

Сортировка пузырьком
const 
    N = 100;
var
    A : array [1..N] of integer;
    I, J : integer;
 
procedure BubbleSort;
var
  T: Integer;
begin
  for I := N downto 1 do
    for J := 1 to N-1 do
      if A[J] > A[J + 1] then
      begin
        T := A[J];
        A[J] := A[J + 1];
        A[J + 1] := T;
      end;
end;
 
begin
   Randomize;
   for I := 1 to N do A[I] := random(N);
   for I := 1 to N do write(A[I],' ');
   writeln; writeln;
   BubbleSort;
   for I := 1 to N do write(A[I],' ');
end.
Сортировка пузырьком
class BubbleSort{
   static float[] sort(float[] a){
      for(int i = a.length - 1; i >= 0; i--){
         for (int j = 0; j < a.length - 1; j++){
            if (a[j] > a[j+1]){
               float tmp = a[j];
               a[j] = a[j+1];
               a[j+1] = tmp;
            }
         }
      }
      return a;
   }
   public static void main(String[] args) {
      int N = 100;
      float a[];
      a = new float[N];
      for(int i = 0; i < a.length; i++){
         a[i] = (float)Math.random() * 100;
      }
      a = sort(a);
   }
}

Сортировка выбором

<flashplayer width=320 height=260>file=http://wiki.nsunc.com/_media/sorting/select-sort.flv</flashplayer>

Сортировка выбором
const 
    N = 100;
var
    A : array [1..N] of integer;
    I, J : integer;
 
procedure SelectionSort;
var
    T: Integer;
begin
  for I := 1 to N-1 do
    for J := N downto I+1 do
      if A[I] > A[J] then
      begin
        T := A[I];
        A[I] := A[J];
        A[J] := T;
      end;
end;
 
begin
   Randomize;
   for I := 1 to N do A[I] := random(N);
   for I := 1 to N do write(A[I],' ');
   writeln; writeln;
   SelectionSort;
   for I := 1 to N do write(A[I],' ');
end.

Быстрая сортировка

<flashplayer width=320 height=260>file=http://wiki.nsunc.com/_media/sorting/quick-sort.flv</flashplayer>

Быстрая сортировка
const 
    N = 100;
var
    A : array [1..N] of integer;
    I, J : integer;
 
procedure QuickSort;
 
  procedure QSort(iLo, iHi: Integer);
  var
    Lo, Hi, Mid, T: Integer;
  begin
    Lo := iLo;
    Hi := iHi;
    Mid := A[(Lo + Hi) div 2];
    repeat
      while A[Lo] < Mid do Inc(Lo);
      while A[Hi] > Mid do Dec(Hi);
      if Lo <= Hi then
      begin
        T := A[Lo];
        A[Lo] := A[Hi];
        A[Hi] := T;
        Inc(Lo);
        Dec(Hi);
      end;
    until Lo > Hi;
    if Hi > iLo then QSort(iLo, Hi);
    if Lo < iHi then QSort(Lo, iHi);
  end;
 
begin
  QSort(1, N);
end;
 
begin
   Randomize;
   for I := 1 to N do A[I] := random(N);
   for I := 1 to N do write(A[I],' ');
   writeln; writeln;
   QuickSort;
   for I := 1 to N do write(A[I],' ');
end.

Другие алгоритмы

Другие алгоритмы сортировки