Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Semrush - keyword research tool

Create your online store today with Shopify

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Disclosure: My content contains affiliate links.

43,226 questions

56,128 answers

573 users

How to sort an array with a single loop in Pascal

1 Answer

0 votes
program SingleLoopSortProgram;

{$mode objfpc}{$H+}{$J-}


// Generic array type definition for standard dynamic integer arrays
type
  TIntArray = array of Integer;

{ Reads and swaps two integer values in place using built-in system routines. }
procedure SwapValues(var A, B: Integer);
var
  Temp: Integer;
begin
  Temp := A;
  A := B;
  B := Temp;
end;

{ Prints all elements of a dynamic array on a single line. }
procedure PrintArray(const Arr: TIntArray);
var
  I: Integer;
begin
  for I := Low(Arr) to High(Arr) do
  begin
    Write(Arr[I]);
    if I < High(Arr) then
      Write(' ');
  end;
  WriteLn;
end;

{
  Sorts a dynamic array in-place in non-decreasing order using Gnome Sort.

  Algorithm Logic (Single Loop):
  - Traverses the array using a single while loop index.
  - Advances forward if adjacent elements are already in non-decreasing order.
  - When an out-of-order adjacent pair is encountered, swaps the elements 
    and steps backward one index to verify order against previous items.
  - Time Complexity: O(N) best case (already sorted), O(N^2) worst case.
  - Space Complexity: O(1) auxiliary space.
}
procedure SingleLoopSort(var Arr: TIntArray);
var
  Pos: Integer;
  Len: Integer;
begin
  Len := Length(Arr);
  Pos := 0;

  while Pos < Len do
  begin
    // Move forward if at the beginning or if the current pair is sorted
    if (Pos = 0) or (Arr[Pos] >= Arr[Pos - 1]) then
      Inc(Pos)
    else
    begin
      // Swap adjacent out-of-order elements and step backward
      SwapValues(Arr[Pos], Arr[Pos - 1]);
      Dec(Pos);
    end;
  end;
end;

var
  Numbers: TIntArray;
begin
  // Initialize dynamic array with standard array literal syntax
  Numbers := TIntArray.Create(42, -5, 12, 0, 89, -18, 33, 7);

  WriteLn('Original array:');
  PrintArray(Numbers);

  SingleLoopSort(Numbers);

  WriteLn;
  WriteLn('Sorted array:');
  PrintArray(Numbers);
end.


(*
run:

Original array:
42 -5 12 0 89 -18 33 7

Sorted array:
-18 -5 0 7 12 33 42 89

*)

 



answered Aug 8 by avibootz
...