VOOZH about

URL: https://www.geeksforgeeks.org/dsa/rearrange-array-order-smallest-largest-2nd-smallest-2nd-largest/

⇱ Rearrange an array in order - smallest, largest, 2nd smallest, 2nd largest, .. - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Rearrange an array in order - smallest, largest, 2nd smallest, 2nd largest, ..

Last Updated : 21 Aug, 2022

Given an array of integers, the task is to print the array in the order - smallest number, the Largest number, 2nd smallest number, 2nd largest number, 3rd smallest number, 3rd largest number, and so on.....

Examples:  

Input : arr[] = [5, 8, 1, 4, 2, 9, 3, 7, 6]
Output :arr[] = {1, 9, 2, 8, 3, 7, 4, 6, 5}

Input : arr[] = [1, 2, 3, 4]
Output :arr[] = {1, 4, 2, 3}

A simple solution is to first find the smallest element and swap it with the first element. Then find the largest element, swap it with the second element, and so on. The time complexity of this solution is O(n2).

An efficient solution is to use sorting

  1. Sort the elements of the array. 
  2. Take two variables say i and j and point them to the first and last index of the array respectively. 
  3. Now run a loop and store the elements in the array one by one by incrementing i and decrementing j.

Let's take an array with input 5, 8, 1, 4, 2, 9, 3, 7, 6 and sort them so the array becomes 1, 2, 3, 4, 5, 6, 7, 8, 9. Now take two variables to say i and j and point them to the first and last index of the array respectively, run a loop, and store the value into a new array by incrementing I and decrementing j.get that the final result as 1 9 2 8 3 7 4 6 5. 

The flowchart is as follows:

👁 Image
flowchart- rearrangearray

Implementation:


Output
1 9 2 8 3 7 4 6 5 

Time Complexity: O(n log n), 

Auxiliary Space: O(n), since n extra space has been taken.

Comment
Article Tags: