Alternative Sorting (original) (raw)
Last Updated : 12 May, 2026
Given an **arr[] of **distinct integers. Rearrange the array in such a way that the first element is the largest and the second element is the smallest, the third element is the second largest and the fourth element is the second smallest, and so on.
**Examples :
**Input: arr[] = [7, 1, 2, 3, 4, 5, 6]
**Output: [7, 1, 6, 2, 5, 3, 4]
**Explanation: The first element is first maximum and second element is first minimum and so on.**Input: arr[] = [1, 6, 9, 4, 3, 7, 8, 2]
**Output: [9, 1, 8, 2, 7, 3, 6, 4]
**Explanation: The first element is first maximum and second element is first minimum and so on.
Table of Content
- [Naive Approach] Using Nested Loops - O(n^2) Time and O(n) Space
- [Efficient Approach] Using Sorting and Two Pointers – O(n log n) Time and O(1) Space
[Naive Approach] Using Nested Loops - O(n^2) Time and O(n) Space
The idea is to find the maximum element, then the minimum, then the next maximum, and so on, by repeatedly scanning the array to find the next unvisited max or min using visited Array.
C++ `
#include #include #include using namespace std;
vector alternateSort(vector &arr) {
int n = arr.size();
// To keep track of visited elements
vector<bool> visited(n, false);
// To store the final result
vector<int> res;
// Iterate n times to pick elements alternately
for (int count = 0; count < n; count++)
{
int index = -1;
// If count is even, pick maximum element
if (count % 2 == 0)
{
// Initialize maximum value
int maxVal = INT_MIN;
// Find maximum unvisited element
for (int i = 0; i < n; i++)
{
if (!visited[i] && arr[i] > maxVal)
{
maxVal = arr[i];
index = i;
}
}
}
else
{
// Initialize minimum value
int minVal = INT_MAX;
// Find minimum unvisited element
for (int i = 0; i < n; i++)
{
if (!visited[i] && arr[i] < minVal)
{
minVal = arr[i];
index = i;
}
}
}
// Add selected element to result and mark it visited
if (index != -1)
{
res.push_back(arr[index]);
visited[index] = true;
}
}
// Return the final alternately sorted array
return res;}
// Driver code int main() {
vector<int> arr = {7, 1, 2, 3, 4, 5, 6};
vector<int> res = alternateSort(arr);
for (int i = 0; i < res.size(); i++) {
cout << res[i] << " ";
}
return 0;}
Java
import java.util.ArrayList; import java.util.Arrays;
public class GfG { public static ArrayList alternateSort(int[] arr) { int n = arr.length; boolean[] visited = new boolean[n]; ArrayList res = new ArrayList<>();
for (int count = 0; count < n; count++) {
int index = -1;
if (count % 2 == 0) {
int maxVal = Integer.MIN_VALUE;
for (int i = 0; i < n; i++) {
if (!visited[i] && arr[i] > maxVal) {
maxVal = arr[i];
index = i;
}
}
} else {
int minVal = Integer.MAX_VALUE;
for (int i = 0; i < n; i++) {
if (!visited[i] && arr[i] < minVal) {
minVal = arr[i];
index = i;
}
}
}
if (index!= -1) {
res.add(arr[index]);
visited[index] = true;
}
}
return res;
}
public static void main(String[] args) {
int[] arr = {7, 1, 2, 3, 4, 5, 6};
ArrayList<Integer> res = alternateSort(arr);
for (int i = 0; i < res.size(); i++) {
System.out.print(res.get(i) + " ");
}
}}
Python
def alternateSort(arr): n = len(arr) visited = [False] * n res = []
for count in range(n):
index = -1
if count % 2 == 0:
maxVal = float('-inf')
for i in range(n):
if not visited[i] and arr[i] > maxVal:
maxVal = arr[i]
index = i
else:
minVal = float('inf')
for i in range(n):
if not visited[i] and arr[i] < minVal:
minVal = arr[i]
index = i
if index!= -1:
res.append(arr[index])
visited[index] = True
return resDriver code
arr = [7, 1, 2, 3, 4, 5, 6] res = alternateSort(arr)
for i in range(len(res)): print(res[i], end=' ')
print()
C#
using System; using System.Collections.Generic;
public class Program{ public static List alternateSort(int[] arr){ int n = arr.Length; bool[] visited = new bool[n]; List res = new List();
for (int count = 0; count < n; count++){
int index = -1;
if (count % 2 == 0){
int maxVal = int.MinValue;
for (int i = 0; i < n; i++){
if (!visited[i] && arr[i] > maxVal){
maxVal = arr[i];
index = i;
}
}
} else {
int minVal = int.MaxValue;
for (int i = 0; i < n; i++){
if (!visited[i] && arr[i] < minVal){
minVal = arr[i];
index = i;
}
}
}
if (index!= -1){
res.Add(arr[index]);
visited[index] = true;
}
}
return res;
}
public static void Main(){
int[] arr = {7, 1, 2, 3, 4, 5, 6};
List<int> res = alternateSort(arr);
for (int i = 0; i < res.Count; i++){
Console.Write(res[i] + " ");
}
Console.WriteLine();
}}
JavaScript
function alternateSort(arr) { let n = arr.length; let visited = Array(n).fill(false); let res = [];
for (let count = 0; count < n; count++) {
let index = -1;
if (count % 2 === 0) {
let maxVal = Number.MIN_SAFE_INTEGER;
for (let i = 0; i < n; i++) {
if (!visited[i] && arr[i] > maxVal) {
maxVal = arr[i];
index = i;
}
}
} else {
let minVal = Number.MAX_SAFE_INTEGER;
for (let i = 0; i < n; i++) {
if (!visited[i] && arr[i] < minVal) {
minVal = arr[i];
index = i;
}
}
}
if (index!== -1) {
res.push(arr[index]);
visited[index] = true;
}
}
return res;}
// Driver code let arr = [7, 1, 2, 3, 4, 5, 6]; let res = alternateSort(arr);
for (let i = 0; i < res.length; i++) { process.stdout.write(res[i] + ' '); }
console.log();
`
**Time Complexity: O(n^2)
**Space Complexity: O(n)
[Efficient Approach] Using Sorting and Two Pointers – O(n log n) Time and O(1) Space
The idea is to first sort the array. After sorting, we initialize two pointers - one at the beginning and one at the end. In each step, we add the largest and smallest remaining elements alternately to the result by moving the right pointer leftward and the left pointer rightward.
**Let us understand with an example:
**Input: arr[] = [7, 1, 2, 3, 4, 5, 6]
After sorting -> [1, 2, 3, 4, 5, 6, 7]
Start: res = []
- At i = 0, j = 6 -> pick 7 and 1 -> res = [7, 1]
- At i = 1, j = 5 -> pick 6 and 2 -> res = [7, 1, 6, 2]
- At i = 2, j = 4 -> pick 5 and 3 -> res = [7, 1, 6, 2, 5, 3]
So, i = j = 3 -> pick 4 -> res = [7, 1, 6, 2, 5, 3, 4]
Then Stop, **Output : 7 1 6 2 5 3 4
C++ `
#include #include #include using namespace std;
vector alternateSort(vector &arr) {
int n = arr.size();
// Sorting the array in ascending order
sort(arr.begin(), arr.end());
vector<int> res;
int i = 0, j = n - 1;
// Pick elements alternately from end and start
while (i < j)
{
// Add from the end (maximum)
res.push_back(arr[j--]);
// Add from the beginning (minimum)
res.push_back(arr[i++]);
}
// If odd number of elements, add the middle element
if (n % 2 != 0)
res.push_back(arr[i]);
return res;}
// Driver Code int main() {
vector<int> arr = {7, 1, 2, 3, 4, 5, 6};
vector<int> res = alternateSort(arr);
// Print the result
for (int i = 0; i < res.size(); i++) {
cout << res[i] << " ";
}
cout << endl;
return 0;}
Java
import java.util.*;
public class GfG {
public static ArrayList<Integer> alternateSort(int[] arr) {
int n = arr.length;
// Convert int[] to ArrayList
ArrayList<Integer> list = new ArrayList<>();
for (int x : arr)
list.add(x);
// Sort
Collections.sort(list);
ArrayList<Integer> res = new ArrayList<>();
int i = 0, j = n - 1;
// Alternate max-min
while (i < j) {
res.add(list.get(j--));
res.add(list.get(i++));
}
// If odd
if (n % 2 != 0)
res.add(list.get(i));
return res;
}
public static void main(String[] args) {
int[] arr = {7, 1, 2, 3, 4, 5, 6};
ArrayList<Integer> res = alternateSort(arr);
for (int x : res) {
System.out.print(x + " ");
}
}}
Python
from typing import List
def alternateSort(arr: List[int]) -> List[int]:
n = len(arr)
# Sorting the array in ascending order
arr.sort()
res = []
i = 0
j = n - 1
# Pick elements alternately from end and start
while i < j:
# Add from the end (maximum)
res.append(arr[j])
j -= 1
# Add from the beginning (minimum)
res.append(arr[i])
i += 1
# If odd number of elements, add the middle element
if n % 2!= 0:
res.append(arr[i])
return resDriver Code
if name == "main":
arr = [7, 1, 2, 3, 4, 5, 6]
res = alternateSort(arr)
for i in res:
print(i, end=' ')C#
using System; using System.Collections.Generic; using System.Linq;
public class GfG { public static List alternateSort(List arr) { int n = arr.Count;
// Sorting the array in ascending order
arr.Sort();
List<int> res = new List<int>();
int i = 0, j = n - 1;
// Pick elements alternately from end and start
while (i < j)
{
// Add from the end (maximum)
res.Add(arr[j--]);
// Add from the beginning (minimum)
res.Add(arr[i++]);
}
// If odd number of elements, add the middle element
if (n % 2!= 0)
res.Add(arr[i]);
return res;
}
public static void Main()
{
List<int> arr = new List<int>{7, 1, 2, 3, 4, 5, 6};
List<int> res = alternateSort(arr);
for (int i = 0; i < res.Count; i++) {
Console.Write(res[i] + " ");
}
}}
JavaScript
function alternateSort(arr) { let n = arr.length;
// Sorting the array in ascending order
arr.sort((a, b) => a - b);
let res = [];
let i = 0, j = n - 1;
// Pick elements alternately from end and start
while (i < j) {
// Add from the end (maximum)
res.push(arr[j--]);
// Add from the beginning (minimum)
res.push(arr[i++]);
}
// If odd number of elements, add the middle element
if (n % 2!= 0)
res.push(arr[i]);
return res;}
// Driver code let arr = [7, 1, 2, 3, 4, 5, 6]; let res = alternateSort(arr); for (let i = 0; i < res.length; i++) { console.log(res[i] + ' '); }
`
**Time Complexity: O(n log n)
**Space Complexity: O(n)