How to resolve the algorithm Sorting Algorithms/Circle Sort step by step in the Delphi programming language

Published on 12 May 2024 09:40 PM

How to resolve the algorithm Sorting Algorithms/Circle Sort step by step in the Delphi programming language

Table of Contents

Problem Statement

Sort an array of integers (of any convenient size) into ascending order using Circlesort. In short, compare the first element to the last element, then the second element to the second last element, etc. Then split the array in two and recurse until there is only one single element in the array, like this: Repeat this procedure until quiescence (i.e. until there are no swaps). Show both the initial, unsorted list and the final sorted list. (Intermediate steps during sorting are optional.) Optimizations (like doing 0.5 log2(n) iterations and then continue with an Insertion sort) are optional. Pseudo code:

Let's start with the solution:

Step by Step solution about How to resolve the algorithm Sorting Algorithms/Circle Sort step by step in the Delphi programming language

Source code in the delphi programming language

program Sorting_Algorithms;

{$APPTYPE CONSOLE}

uses
  System.SysUtils;

function CircleSort(a: TArray; lo, hi, swaps: Integer): Integer;
begin
  if lo = hi then
    exit(swaps);

  var high := hi;
  var low := lo;
  var mid := (hi - lo) div 2;

  while lo < hi do
  begin
    if a[lo] > a[hi] then
    begin
      var tmp := a[lo];
      a[lo] := a[hi];
      a[hi] := tmp;
      inc(swaps);
    end;
    inc(lo);
    dec(hi);
  end;

  if lo = hi then
  begin
    if a[lo] > a[hi + 1] then
    begin
      var tmp := a[lo];
      a[lo] := a[hi + 1];
      a[hi + 1] := tmp;
      inc(swaps);
    end;
  end;
  swaps := CircleSort(a, low, low + mid, swaps);
  swaps := CircleSort(a, low + mid + 1, high, swaps);
  result := swaps;
end;

function ToString(a: TArray): string;
begin
  Result := '[';
  for var e in a do
    Result := Result + e.ToString + ',';
  Result := Result + ']';
end;

const
  aa: TArray> = [[6, 7, 8, 9, 2, 5, 3, 4, 1], [2, 14, 4, 6, 8, 1,
    3, 5, 7, 11, 0, 13, 12, -1]];

begin
  for var a in aa do
  begin
    write('Original: ');
    write(ToString(a));
    while CircleSort(a, 0, high(a), 0) <> 0 do
      ;
    writeln;
    write('Sorted  : ');
    write(ToString(a));
    writeln(#10#10);
  end;
  readln;
end.


  

You may also check:How to resolve the algorithm Topswops step by step in the C++ programming language
You may also check:How to resolve the algorithm Copy a string step by step in the Forth programming language
You may also check:How to resolve the algorithm Convert decimal number to rational step by step in the PL/I programming language
You may also check:How to resolve the algorithm Read entire file step by step in the Elixir programming language
You may also check:How to resolve the algorithm Cartesian product of two or more lists step by step in the D programming language