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.
- Sort the elements of the array.
- Take two variables say i and j and point them to the first and last index of the array respectively.
- 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:
flowchart- rearrangearray
Implementation:
C++
// C++ program to print the array in given order
#include <bits/stdc++.h>
using namespace std;
// Function which arrange the array.
void rearrangeArray(int arr[], int n)
{
// Sorting the array elements
sort(arr, arr + n);
int tempArr[n]; // To store modified array
// Adding numbers from sorted array to
// new array accordingly
int ArrIndex = 0;
// Traverse from begin and end simultaneously
for (int i = 0, j = n - 1; i <= n / 2 || j > n / 2;
i++, j--) {
tempArr[ArrIndex] = arr[i];
ArrIndex++;
tempArr[ArrIndex] = arr[j];
ArrIndex++;
}
// Modifying original array
for (int i = 0; i < n; i++)
arr[i] = tempArr[i];
}
// Driver Code
int main()
{
int arr[] = { 5, 8, 1, 4, 2, 9, 3, 7, 6 };
int n = sizeof(arr) / sizeof(arr[0]);
rearrangeArray(arr, n);
for (int i = 0; i < n; i++)
cout << arr[i] << " ";
return 0;
}
Java
// Java program to print the array in given order
import java.util.Arrays;
public class GFG {
// Function which arrange the array.
static void rearrangeArray(int arr[], int n)
{
// Sorting the array elements
Arrays.sort(arr);
int[] tempArr = new int[n]; // To store modified array
// Adding numbers from sorted array to
// new array accordingly
int ArrIndex = 0;
// Traverse from begin and end simultaneously
for (int i = 0, j = n-1; i <= n / 2 || j > n / 2;
i++, j--) {
if(ArrIndex < n)
{
tempArr[ArrIndex] = arr[i];
ArrIndex++;
}
if(ArrIndex < n)
{
tempArr[ArrIndex] = arr[j];
ArrIndex++;
}
}
// Modifying original array
for (int i = 0; i < n; i++)
arr[i] = tempArr[i];
}
// Driver Code
public static void main(String args[])
{
int arr[] = { 5, 8, 1, 4, 2, 9, 3, 7, 6 };
int n = arr.length;
rearrangeArray(arr, n);
for (int i = 0; i < n; i++)
System.out.print(arr[i]+" ");
}
}
// This code is contributed by Sumit Ghosh
Python3
# Python 3 program to print
# the array in given order
# Function which arrange the
# array.
def rearrangeArray(arr, n) :
# Sorting the array elements
arr.sort()
# To store modified array
tempArr = [0] * (n + 1)
# Adding numbers from sorted
# array to new array accordingly
ArrIndex = 0
# Traverse from begin and end
# simultaneously
i = 0
j = n-1
while(i <= n // 2 or j > n // 2 ) :
tempArr[ArrIndex] = arr[i]
ArrIndex = ArrIndex + 1
tempArr[ArrIndex] = arr[j]
ArrIndex = ArrIndex + 1
i = i + 1
j = j - 1
# Modifying original array
for i in range(0, n) :
arr[i] = tempArr[i]
# Driver Code
arr = [ 5, 8, 1, 4, 2, 9, 3, 7, 6 ]
n = len(arr)
rearrangeArray(arr, n)
for i in range(0, n) :
print( arr[i], end = " ")
# This code is contributed by Nikita Tiwari.
C#
// C# program to print the
// array in given order
using System;
public class GFG {
// Function which arrange the array.
static void rearrangeArray(int []arr, int n)
{
// Sorting the array elements
Array.Sort(arr);
// To store modified array
int []tempArr = new int[n];
// Adding numbers from sorted array
// to new array accordingly
int ArrIndex = 0;
// Traverse from begin and end simultaneously
for (int i = 0, j = n-1; i <= n / 2
|| j > n / 2; i++, j--) {
if(ArrIndex < n)
{
tempArr[ArrIndex] = arr[i];
ArrIndex++;
}
if(ArrIndex < n)
{
tempArr[ArrIndex] = arr[j];
ArrIndex++;
}
}
// Modifying original array
for (int i = 0; i < n; i++)
arr[i] = tempArr[i];
}
// Driver Code
public static void Main(String []args)
{
int []arr = {5, 8, 1, 4, 2, 9, 3, 7, 6};
int n = arr.Length;
rearrangeArray(arr, n);
for (int i = 0; i < n; i++)
Console.Write(arr[i] + " ");
}
}
// This code is contributed by Nitin Mittal.
PHP
<?php
// PHP program to print
// the array in given order
// Function which
// arrange the array.
function rearrangeArray($arr, $n)
{
// Sorting the
// array elements
sort($arr);
// To store modified array
$tempArr = array($n);
// Adding numbers from
// sorted array to new
// array accordingly
$ArrIndex = 0;
// Traverse from begin
// and end simultaneously
for ($i = 0, $j = $n - 1;
$i <= $n / 2 || $j > $n / 2;
$i++, $j--)
{
$tempArr[$ArrIndex] = $arr[$i];
$ArrIndex++;
$tempArr[$ArrIndex] = $arr[$j];
$ArrIndex++;
}
// Modifying original array
for ($i = 0; $i < $n; $i++)
$arr[$i] = $tempArr[$i];
for ($i = 0; $i < $n; $i++)
echo $arr[$i] . " ";
}
// Driver Code
$arr = array(5, 8, 1, 4, 2,
9, 3, 7, 6 );
$n = count($arr) ;
rearrangeArray($arr, $n);
// This code is contributed
// by Sam007
?>
JavaScript
<script>
// Javascript program to print the
// array in given order
// Function which arrange the array.
function rearrangeArray(arr, n)
{
// Sorting the array elements
arr.sort();
// To store modified array
let tempArr = new Array(n);
// Adding numbers from sorted array
// to new array accordingly
let ArrIndex = 0;
// Traverse from begin and end simultaneously
for (let i = 0, j = n-1; i <= n / 2
|| j > n / 2; i++, j--) {
if(ArrIndex < n)
{
tempArr[ArrIndex] = arr[i];
ArrIndex++;
}
if(ArrIndex < n)
{
tempArr[ArrIndex] = arr[j];
ArrIndex++;
}
}
// Modifying original array
for (let i = 0; i < n; i++)
arr[i] = tempArr[i];
}
// Driver Code
let arr =[5, 8, 1, 4, 2, 9, 3, 7, 6]
let n = arr.length;
rearrangeArray(arr, n);
for (let i = 0; i < n; i++)
document.write(arr[i] + " ");
</script>
Time Complexity: O(n log n),
Auxiliary Space: O(n), since n extra space has been taken.
Similar Reads
DSA Tutorial - Learn Data Structures and Algorithms DSA (Data Structures and Algorithms) is the study of organizing data efficiently using data structures like arrays, stacks, and trees, paired with step-by-step procedures (or algorithms) to solve problems effectively. Data structures manage how data is stored and accessed, while algorithms focus on
7 min read
Quick Sort QuickSort is a sorting algorithm based on the Divide and Conquer that picks an element as a pivot and partitions the given array around the picked pivot by placing the pivot in its correct position in the sorted array. It works on the principle of divide and conquer, breaking down the problem into s
12 min read
Merge Sort - Data Structure and Algorithms Tutorials Merge sort is a popular sorting algorithm known for its efficiency and stability. It follows the divide-and-conquer approach. It works by recursively dividing the input array into two halves, recursively sorting the two halves and finally merging them back together to obtain the sorted array. Merge
14 min read
SQL Commands | DDL, DQL, DML, DCL and TCL Commands SQL commands are crucial for managing databases effectively. These commands are divided into categories such as Data Definition Language (DDL), Data Manipulation Language (DML), Data Control Language (DCL), Data Query Language (DQL), and Transaction Control Language (TCL). In this article, we will e
7 min read
Bubble Sort Algorithm Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. This algorithm is not suitable for large data sets as its average and worst-case time complexity are quite high.We sort the array using multiple passes. After the fir
8 min read
Data Structures Tutorial Data structures are the fundamental building blocks of computer programming. They define how data is organized, stored, and manipulated within a program. Understanding data structures is very important for developing efficient and effective algorithms. What is Data Structure?A data structure is a st
2 min read
Breadth First Search or BFS for a Graph Given a undirected graph represented by an adjacency list adj, where each adj[i] represents the list of vertices connected to vertex i. Perform a Breadth First Search (BFS) traversal starting from vertex 0, visiting vertices from left to right according to the adjacency list, and return a list conta
15+ min read
Binary Search Algorithm - Iterative and Recursive Implementation Binary Search Algorithm is a searching algorithm used in a sorted array by repeatedly dividing the search interval in half. The idea of binary search is to use the information that the array is sorted and reduce the time complexity to O(log N). Binary Search AlgorithmConditions to apply Binary Searc
15 min read
Insertion Sort Algorithm Insertion sort is a simple sorting algorithm that works by iteratively inserting each element of an unsorted list into its correct position in a sorted portion of the list. It is like sorting playing cards in your hands. You split the cards into two groups: the sorted cards and the unsorted cards. T
9 min read
Dijkstra's Algorithm to find Shortest Paths from a Source to all Given a weighted undirected graph represented as an edge list and a source vertex src, find the shortest path distances from the source vertex to all other vertices in the graph. The graph contains V vertices, numbered from 0 to V - 1.Note: The given graph does not contain any negative edge. Example
12 min read