Check if it is possible to sort an array with conditional swapping of adjacent allowed
Last Updated :
11 Jul, 2022
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 : arr[] = {1, 0, 3, 2}
Output : yes
Explanation:- We can swap arr[0] and arr[1].
Again we swap arr[2] and arr[3].
Final arr[] = {0, 1, 2, 3}.
Input : arr[] = {2, 1, 0}
Output : no
Although the problems looks complex at first look, there is a simple solution to it. If we traverse array from left to right and we make sure elements before an index i are sorted before we reach i, we must have maximum of arr[0..i-1] just before i. And this maximum must be either smaller than arr[i] or just one greater than arr[i]. In first case, we simply move ahead. In second case, we swap and move ahead.
Compare the current element with the next element in array.If current element is greater than next element then do following:-
- Check if difference between two numbers is 1 then swap it.
- else Return false.
If we reach end of array, we return true.
C++
// C++ program to check if we can sort
// an array with adjacent swaps allowed
#include<bits/stdc++.h>
using namespace std;
// Returns true if it is possible to sort
// else false/
bool checkForSorting(int arr[], int n)
{
for (int i=0; i<n-1; i++)
{
// We need to do something only if
// previousl element is greater
if (arr[i] > arr[i+1])
{
if (arr[i] - arr[i+1] == 1)
swap(arr[i], arr[i+1]);
// If difference is more than
// one, then not possible
else
return false;
}
}
return true;
}
// Driver code
int main()
{
int arr[] = {1,0,3,2};
int n = sizeof(arr)/sizeof(arr[0]);
if (checkForSorting(arr, n))
cout << "Yes";
else
cout << "No";
}
Java
class Main
{
// Returns true if it is possible to sort
// else false/
static boolean checkForSorting(int arr[], int n)
{
for (int i=0; i<n-1; i++)
{
// We need to do something only if
// previousl element is greater
if (arr[i] > arr[i+1])
{
if (arr[i] - arr[i+1] == 1)
{
// swapping
int temp = arr[i];
arr[i] = arr[i+1];
arr[i+1] = temp;
}
// If difference is more than
// one, then not possible
else
return false;
}
}
return true;
}
// Driver function
public static void main(String args[])
{
int arr[] = {1,0,3,2};
int n = arr.length;
if (checkForSorting(arr, n))
System.out.println("Yes");
else
System.out.println("No");
}
}
Python3
# Python 3 program to
# check if we can sort
# an array with adjacent
# swaps allowed
# Returns true if it
# is possible to sort
# else false/
def checkForSorting(arr, n):
for i in range(0,n-1):
# We need to do something only if
# previousl element is greater
if (arr[i] > arr[i+1]):
if (arr[i] - arr[i+1] == 1):
arr[i], arr[i+1] = arr[i+1], arr[i]
# If difference is more than
# one, then not possible
else:
return False
return True
# Driver code
arr = [1,0,3,2]
n = len(arr)
if (checkForSorting(arr, n)):
print("Yes")
else:
print("No")
# This code is contributed by
# Smitha Dinesh Semwal
C#
// C# program to check if we can sort
// an array with adjacent swaps allowed
using System;
class GFG
{
// Returns true if it is
// possible to sort else false
static bool checkForSorting(int []arr, int n)
{
for (int i=0; i<n-1; i++)
{
// We need to do something only if
// previousl element is greater
if (arr[i] > arr[i+1])
{
if (arr[i] - arr[i+1] == 1)
{
// swapping
int temp = arr[i];
arr[i] = arr[i+1];
arr[i+1] = temp;
}
// If difference is more than
// one, then not possible
else
return false;
}
}
return true;
}
// Driver function
public static void Main()
{
int []arr = {1, 0, 3, 2};
int n = arr.Length;
if (checkForSorting(arr, n))
Console.Write("Yes");
else
Console.Write("No");
}
}
// This code is contributed by nitin mittal.
PHP
<?php
// PHP program to check if we can sort
// an array with adjacent swaps allowed
// Returns true if it is possible to sort
// else false
function checkForSorting($arr, $n)
{
$temp = 0;
for ($i = 0; $i < $n - 1; $i++)
{
// We need to do something only if
// previousl element is greater
if ($arr[$i] > $arr[$i + 1])
{
if ($arr[$i] - $arr[$i + 1] == 1)
{
// swapping
$temp = $arr[$i];
$arr[$i] = $arr[$i + 1];
$arr[$i + 1] = $temp;
}
// If difference is more than
// one, then not possible
else
return false;
}
}
return true;
}
// Driver Code
$arr = array(1,0,3,2);
$n = sizeof($arr);
if (checkForSorting($arr, $n))
echo "Yes";
else
echo "No";
// This code is contributed
// by nitin mittal.
?>
JavaScript
<script>
// JavaScript program to check if we can sort
// an array with adjacent swaps allowed
// Returns true if it is possible to sort
// else false
function checkForSorting(arr, n)
{
let temp = 0;
for (let i = 0; i < n - 1; i++)
{
// We need to do something only if
// previousl element is greater
if (arr[i] > arr[i + 1])
{
if (arr[i] - arr[i + 1] == 1)
{
// swapping
temp = arr[i];
arr[i] = arr[i + 1];
arr[i + 1] = temp;
}
// If difference is more than
// one, then not possible
else
return false;
}
}
return true;
}
// Driver Code
let arr = new Array(1,0,3,2);
let n = arr.length;
if (checkForSorting(arr, n))
document.write("Yes");
else
document.write("No");
// This code is contributed
// by nitin gfgking
</script>
Time Complexity=O(n)
Auxiliary Space=O(1)
Similar Reads
Sorting Algorithms A Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to Sorting Techniques â Data Structure and Algorithm Tutorials Sorting refers to rearrangement of a given array or list of elements according to a comparison operator on the elements. The comparison operator is used to decide the new order of elements in the respective data structure. Why Sorting Algorithms are ImportantThe sorting algorithm is important in Com
3 min read
Most Common Sorting Algorithms
Selection Sort Selection Sort is a comparison-based sorting algorithm. It sorts an array by repeatedly selecting the smallest (or largest) element from the unsorted portion and swapping it with the first unsorted element. This process continues until the entire array is sorted.First we find the smallest element an
8 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
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
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
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
Heap Sort - Data Structures and Algorithms Tutorials Heap sort is a comparison-based sorting technique based on Binary Heap Data Structure. It can be seen as an optimization over selection sort where we first find the max (or min) element and swap it with the last (or first). We repeat the same process for the remaining elements. In Heap Sort, we use
14 min read
Counting Sort - Data Structures and Algorithms Tutorials Counting Sort is a non-comparison-based sorting algorithm. It is particularly efficient when the range of input values is small compared to the number of elements to be sorted. The basic idea behind Counting Sort is to count the frequency of each distinct element in the input array and use that info
9 min read