Sort an array with swapping only with a special element is allowed
Last Updated :
15 Jun, 2022
Given an array of length n + 1, containing elements 1 through n and a space, Requires the use of a given swap (index i, index j) function to sort the array, You can only swap the gap and a number, in the end, put the gap at the end.
There will be a number 999 in the array as a gap or space.
Examples:
Input : arr = {1, 5, 4, 999, 3, 2}
Output : arr = {1, 2, 3, 4, 5, 999}
We need to sort only by moving
Input : arr = {1, 5, 4, 3, 2, 8, 7, 999, 6}
Output : arr = {1, 2, 3, 4, 5, 6, 7, 8, 999}
We follow a recursive approach to solve this problem. As we can only swap numbers with the space. First of all, we find the index of space. If the index is the start of the array, then move this space to the second last index by swapping with each number in its right.
If space is neither start of an array nor the last element of the array and the element before it is greater than the element next to space then do the following.
Step 1: Swap space and element next to space
In case of {3, 999, 2} make it {3, 2, 999}
Step 2 : Swap space and greater element
eg-convert {3, 2, 999} to {999, 2, 3}
Otherwise, elements next to the index are sorted and swap it with the previous element. Again call the sort function with the size of an array decreased by 1 and index of space - 1 as we will get one sorted element each time.
C++
// CPP program to sort an array by moving one
// space around.
#include <bits/stdc++.h>
using namespace std;
// n is total number of elements.
// index is index of 999 or space.
// k is number of elements yet to be sorted.
void sortRec(int arr[], int index, int k, int n)
{
// print the sorted array when loop reaches
// the base case
if (k == 0) {
for (int i = 1; i < n; i++)
cout << arr[i] << " ";
cout << 999;
return;
}
// else if k>0 and space is at 0th index swap
// each number with space and store index at
// second last index
else if (k > 0 && index == 0) {
index = n - 2;
for (int i = 1; i <= index; i++) {
arr[i - 1] = arr[i];
}
arr[index] = 999;
}
// if space is neither start of array nor last
// element of array and element before it greater
// than/ the element next to space
if (index - 1 >= 0 && index + 1 < n &&
arr[index - 1] > arr[index + 1]) {
// first swap space and element next to space
// in case of {3, 999, 2} make it {3, 2, 999}
swap(arr[index], arr[index + 1]);
// than swap space and greater element
// convert {3, 2, 999} to {999, 2, 3}
swap(arr[index - 1], arr[index + 1]);
}
else
swap(arr[index], arr[index - 1]);
sortRec(arr, index - 1, k - 1, n);
}
// Wrapper over sortRec.
void sort(int arr[], int n)
{
// Find index of space (or 999)
int index = -1;
for (int i = 0; i < n; i++) {
if (arr[i] == 999) {
index = i;
break;
}
}
// Invalid input
if (index == -1)
return;
sortRec(arr, index, n, n);
}
// driver program
int main()
{
int arr[] = { 3, 2, 999, 1 };
int n = sizeof(arr) / sizeof(arr[0]);
sort(arr, n);
return 0;
}
Java
// Java program to sort an array by moving one
// space around.
class GFG
{
// n is total number of elements.
// index is index of 999 or space.
// k is number of elements yet to be sorted.
static void sortRec(int arr[], int index, int k, int n)
{
// print the sorted array when loop reaches
// the base case
if (k == 0)
{
for (int i = 1; i < n; i++)
System.out.print(arr[i] + " ");
System.out.println(999);
return;
}
// else if k>0 and space is at 0th index swap
// each number with space and store index at
// second last index
else if (k > 0 && index == 0)
{
index = n - 2;
for (int i = 1; i <= index; i++)
{
arr[i - 1] = arr[i];
}
arr[index] = 999;
}
// if space is neither start of array nor last
// element of array and element before it greater
// than/ the element next to space
if (index - 1 >= 0 && index + 1 < n &&
arr[index - 1] > arr[index + 1])
{
// first swap space and element next to space
// in case of {3, 999, 2} make it {3, 2, 999}
swap(arr,index, index + 1);
// than swap space and greater element
// convert {3, 2, 999} to {999, 2, 3}
swap(arr,index - 1, index + 1);
}
else
swap(arr,index, index - 1);
sortRec(arr, index - 1, k - 1, n);
}
static int[] swap(int []arr, int i, int j)
{
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
return arr;
}
// Wrapper over sortRec.
static void sort(int arr[], int n)
{
// Find index of space (or 999)
int index = -1;
for (int i = 0; i < n; i++)
{
if (arr[i] == 999)
{
index = i;
break;
}
}
// Invalid input
if (index == -1)
return;
sortRec(arr, index, n, n);
}
// Driver code
public static void main(String[] args)
{
int arr[] = { 3, 2, 999, 1 };
int n = arr.length;
sort(arr, n);
}
}
// This code contributed by Rajput-Ji
Python3
# Python3 program to sort an array
# by moving one space around.
# n is total number of elements.
# index is index of 999 or space.
# k is number of elements yet to be sorted.
def sortRec(arr, index, k, n):
# Print the sorted array when loop reaches
# the base case
if (k == 0):
for i in range(1,n):
print(arr[i],end=" ")
print(999,end="")
# Else if k>0 and space is at 0th index swap
# each number with space and store index at
# second last index
elif(k > 0 and index == 0):
index = n - 2
for i in range(1,index+1):
arr[i - 1] = arr[i]
arr[index] = 999
# If space is neither start of array nor last
# element of array and element before it greater
# than/ the element next to space
if (index - 1 >= 0 and index + 1 < n and arr[index - 1] > arr[index + 1]):
# First swap space and element next to space
# in case of {3, 999, 2} make it {3, 2, 999}
arr[index],arr[index+1] = arr[index+1],arr[index]
# Than swap space and greater element
# convert {3, 2, 999} to {999, 2, 3}
arr[index-1],arr[index+1] = arr[index+1],arr[index-1]
else:
if(index-1<0):
return
arr[index],arr[index-1] = arr[index-1],arr[index]
sortRec(arr, index - 1, k - 1, n)
# Wrapper over sortRec.
def sort(arr, n):
# Find index of space (or 999)
index = -1
for i in range(n):
if (arr[i] == 999):
index = i
break
# Invalid input
if (index == -1):
return
sortRec(arr, index, n, n)
# Driver Code
arr = [ 3, 2, 999, 1 ]
n=len(arr)
sort(arr, n)
# This code is contributed by rag2127.
C#
// C# program to sort an array by moving one
// space around.
using System;
class GFG
{
// n is total number of elements.
// index is index of 999 or space.
// k is number of elements yet to be sorted.
static void sortRec(int []arr, int index, int k, int n)
{
// print the sorted array when loop reaches
// the base case
if (k == 0)
{
for (int i = 1; i < n; i++)
Console.Write(arr[i] + " ");
Console.WriteLine(999);
return;
}
// else if k>0 and space is at 0th index swap
// each number with space and store index at
// second last index
else if (k > 0 && index == 0)
{
index = n - 2;
for (int i = 1; i <= index; i++)
{
arr[i - 1] = arr[i];
}
arr[index] = 999;
}
// if space is neither start of array nor last
// element of array and element before it greater
// than/ the element next to space
if (index - 1 >= 0 && index + 1 < n &&
arr[index - 1] > arr[index + 1])
{
// first swap space and element next to space
// in case of {3, 999, 2} make it {3, 2, 999}
swap(arr,index, index + 1);
// than swap space and greater element
// convert {3, 2, 999} to {999, 2, 3}
swap(arr,index - 1, index + 1);
}
else
swap(arr,index, index - 1);
sortRec(arr, index - 1, k - 1, n);
}
static int[] swap(int []arr, int i, int j)
{
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
return arr;
}
// Wrapper over sortRec.
static void sort(int []arr, int n)
{
// Find index of space (or 999)
int index = -1;
for (int i = 0; i < n; i++)
{
if (arr[i] == 999)
{
index = i;
break;
}
}
// Invalid input
if (index == -1)
return;
sortRec(arr, index, n, n);
}
// Driver code
public static void Main(String[] args)
{
int []arr = { 3, 2, 999, 1 };
int n = arr.Length;
sort(arr, n);
}
}
// This code has been contributed by 29AjayKumar
JavaScript
<script>
// JavaScript program to sort an array
// by moving one space around.
// n is total number of elements.
// index is index of 999 or space.
// k is number of elements yet to be sorted.
function sortRec(arr, index, k, n)
{
// Print the sorted array when loop reaches
// the base case
if (k == 0)
{
for(let i = 1; i < n; i++)
document.write(arr[i] + " ");
document.write(999);
return;
}
// Else if k>0 and space is at 0th index swap
// each number with space and store index at
// second last index
else if (k > 0 && index == 0)
{
index = n - 2;
for(let i = 1; i <= index; i++)
{
arr[i - 1] = arr[i];
}
arr[index] = 999;
}
// If space is neither start of array nor last
// element of array and element before it greater
// than/ the element next to space
if (index - 1 >= 0 && index + 1 < n &&
arr[index - 1] > arr[index + 1])
{
// First swap space and element next to space
// in case of {3, 999, 2} make it {3, 2, 999}
swap(arr, index, index + 1);
// Than swap space and greater element
// convert {3, 2, 999} to {999, 2, 3}
swap(arr, index - 1, index + 1);
}
else
swap(arr,index, index - 1);
sortRec(arr, index - 1, k - 1, n);
}
function swap(arr, i, j)
{
let temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
return arr;
}
// Wrapper over sortRec.
function sort(arr, n)
{
// Find index of space (or 999)
let index = -1;
for(let i = 0; i < n; i++)
{
if (arr[i] == 999)
{
index = i;
break;
}
}
// Invalid input
if (index == -1)
return;
sortRec(arr, index, n, n);
}
// Driver Code
let arr = [ 3, 2, 999, 1 ];
let n = arr.length;
sort(arr, n);
// This code is contributed by susmitakundugoaldanga
</script>
Output:
1 2 3 999
Time Complexity: O(n2)
Auxiliary Space: O(n)
Similar Reads
Check if it is possible to sort the array without swapping adjacent elements
Given an array arr[] of size N, check if it is possible to sort arr[] without swapping adjacent elements. In other words, check if it is possible to sort arr[] by swapping elements but swapping two consecutive element is not allowed. Examples: Input: N = 4, arr[] = {2, 3, 1, 4}Output: YESExplanation
5 min read
Check if it is possible to sort an array with conditional swapping of adjacent allowed
We are given an unsorted array of integers in the range from 0 to n-1. We are allowed to swap adjacent elements in array many number of times but only if the absolute difference between these element is 1. Check if it is possible to sort the array.If yes then print "yes" else "no". Examples: Input :
5 min read
Sort 1 to N by swapping adjacent elements
Given an array arr[] of size n containing a permutation of the integers from 1 to n, and a binary array brr[] of size n â 1 in which you can swap two adjacent elements arr[i] and arr[i+1] only when brr[i] = 1 and brr[i+1] = 1.Examples:Input: arr[] = [1, 2, 5, 3, 4, 6], brr[] = [0, 1, 1, 1, 0]Output:
10 min read
Sort an array by swapping elements of different type specified by another array
Given two arrays a[] and b[] which contain the integer elements and their respective types (either type 0 or type 1) respectively, the task is to check if it is possible to sort the array in non-decreasing order by swapping elements of different types only. Examples: Input: a[] = {30, 20, 20, 10}, b
9 min read
Number of swaps to sort when only adjacent swapping allowed
Given an array arr[] of non negative integers. We can perform a swap operation on any two adjacent elements in the array. Find the minimum number of swaps needed to sort the array in ascending order. Examples : Input : arr[] = {3, 2, 1}Output : 3We need to do following swaps (3, 2), (3, 1) and (1, 2
13 min read
Sorting array with conditional swapping
Given an array arr containing elements from [1...to n]. Each element appears exactly once in the array arr. Given an string str of length n-1. Each character of the string is either 0 or 1. In the array, swapping of the i-th element with (i + 1)-th element can be done as many times as we want, if th
6 min read
Sort an array by swapping adjacent elements from indices that contains '1' in a given string
Given an array arr[] of size N and a binary string S, the task is to check if it is possible to sort the array arr[] by swapping adjacent array elements, say arr[i] and arr[i + 1] if S[i] is equal to '1'. If it is possible, then print "Yes". Otherwise, print "No". Examples : Input: N = 6, arr[] = {2
7 min read
Print the lexicographically smallest array by swapping elements whose sum is odd
Given an array of N integers. The task is to find the lexicographically smallest array possible by applying the given operation any number of times. The operation is to pick two elements ai and aj (1<=i, j<=N) such that ai + aj is odd, and then swap ai and aj. Examples: Input : a[] = {1, 5, 4,
6 min read
Sort the given Array in Spiral manner starting from the center
Given an array arr[] of size N, the task is to sort the array in descending order starting from the mid of the array having the next largest element at the right of the middle element and the next largest at the left of the middle element and so on. Examples: Input: arr[] = {4, 9, 3, 5, 7}Output: 3
9 min read
Sort a given Array by swapping only pairs with GCD as 1
Given an array arr[], the task is to check if it is possible to sort the given array using any number of operations where at each operation, two elements arr[i] and arr[j] can be swapped if GCD of arr[i] and arr[j] is 1. Example: Input: a = {3, 2, 1}Output: PossibleExplanation: The given array can b
7 min read