How to resolve the algorithm Sorting algorithms/Gnome sort step by step in the Delphi programming language
Published on 12 May 2024 09:40 PM
How to resolve the algorithm Sorting algorithms/Gnome sort step by step in the Delphi programming language
Table of Contents
Problem Statement
Gnome sort is a sorting algorithm which is similar to Insertion sort, except that moving an element to its proper place is accomplished by a series of swaps, as in Bubble Sort. The pseudocode for the algorithm is:
Implement the Gnome sort in your language to sort an array (or list) of numbers.
Let's start with the solution:
Step by Step solution about How to resolve the algorithm Sorting algorithms/Gnome sort step by step in the Delphi programming language
Source code in the delphi programming language
program TestGnomeSort;
{$APPTYPE CONSOLE}
{.$DEFINE DYNARRAY} // remove '.' to compile with dynamic array
type
TItem = Integer; // declare ordinal type for array item
{$IFDEF DYNARRAY}
TArray = array of TItem; // dynamic array
{$ELSE}
TArray = array[0..15] of TItem; // static array
{$ENDIF}
procedure GnomeSort(var A: TArray);
var
Item: TItem;
I, J: Integer;
begin
I:= Low(A) + 1;
J:= Low(A) + 2;
while I <= High(A) do begin
if A[I - 1] <= A[I] then begin
I:= J;
J:= J + 1;
end
else begin
Item:= A[I - 1];
A[I - 1]:= A[I];
A[I]:= Item;
I:= I - 1;
if I = Low(A) then begin
I:= J;
J:= J + 1;
end;
end;
end;
end;
var
A: TArray;
I: Integer;
begin
{$IFDEF DYNARRAY}
SetLength(A, 16);
{$ENDIF}
for I:= Low(A) to High(A) do
A[I]:= Random(100);
for I:= Low(A) to High(A) do
Write(A[I]:3);
Writeln;
GnomeSort(A);
for I:= Low(A) to High(A) do
Write(A[I]:3);
Writeln;
Readln;
end.
You may also check:How to resolve the algorithm Spinning rod animation/Text step by step in the AWK programming language
You may also check:How to resolve the algorithm Verify distribution uniformity/Naive step by step in the JavaScript programming language
You may also check:How to resolve the algorithm Queue/Definition step by step in the Applesoft BASIC programming language
You may also check:How to resolve the algorithm System time step by step in the JavaScript programming language
You may also check:How to resolve the algorithm File extension is in extensions list step by step in the zkl programming language