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,563 questions

56,781 answers

573 users

How to rearrange an array into a zig-zag pattern (a < b > c < d > e < f > g) in Pascal

1 Answer

0 votes
program ZigZagPattern;

// This program rearranges an array into a zig-zag pattern, where the elements 
// alternate between being smaller and larger than their neighbors

// a < b > c < d > e < f > g...
// 3 < 5 > 1 < 9 > 6 < 7 > 2 < 4

procedure Swap(var A, B: Integer);
var
  Temp: Integer;
begin
  Temp := A;
  A := B;
  B := Temp;
end;

procedure RearrangeArrayIntoZigZagPattern(var Arr: array of Integer);
var
  I: Integer;
  Small: Boolean;
begin
  Small := True;

  for I := 0 to High(Arr) - 1 do
  begin
    if Small then
    begin
      { Expect Arr[I] < Arr[I + 1] }
      if Arr[I] > Arr[I + 1] then
        Swap(Arr[I], Arr[I + 1]);
    end
    else
    begin
      { Expect Arr[I] > Arr[I + 1] }
      if Arr[I] < Arr[I + 1] then
        Swap(Arr[I], Arr[I + 1]);
    end;

    Small := not Small;
  end;
end;

var
  Arr: array[0..7] of Integer = (3, 5, 1, 7, 9, 6, 4, 2);
  I: Integer;
begin
  RearrangeArrayIntoZigZagPattern(Arr);

  for I := 0 to High(Arr) do
    Write(Arr[I], ' ');

  Writeln;
end.



{
run:

3 5 1 9 6 7 2 4 

}

 



answered Oct 8 by avibootz
edited Oct 8 by avibootz

Related questions

...