Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Questions on Array
  • Practice Array
  • MCQs on Array
  • Tutorial on Array
  • Types of Arrays
  • Array Operations
  • Subarrays, Subsequences, Subsets
  • Reverse Array
  • Static Vs Arrays
  • Array Vs Linked List
  • Array | Range Queries
  • Advantages & Disadvantages
Open In App
Next Article:
Check if an Array is Sorted
Next article icon

Check if array can be sorted with one swap

Last Updated : 13 Apr, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

Given an array containing N elements. Find if it is possible to sort it in non-decreasing order using atmost one swap.

Examples: 

Input : arr[] = {1, 2, 3, 4} 
Output : YES 
The array is already sorted

Input : arr[] = {3, 2, 1} 
Output : YES 
Swap 3 and 1 to get [1, 2, 3]

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

A simple approach is to sort the array and compare the required position of the element and the current position of the element. If there are no mismatches, the array is already sorted. If there are exactly 2 mismatches, we can swap the terms that are not in the position to get the sorted array.

Implementation:

C++




// CPP program to check if an array can be sorted
// with at-most one swap
#include <bits/stdc++.h>
using namespace std;
 
bool checkSorted(int n, int arr[])
{
    // Create a sorted copy of original array
    int b[n];
    for (int i = 0; i < n; i++)
        b[i] = arr[i];
    sort(b, b + n);
 
    // Check if 0 or 1 swap required to
    // get the sorted array
    int ct = 0;
    for (int i = 0; i < n; i++)
        if (arr[i] != b[i])
            ct++;
    if (ct == 0 || ct == 2)
        return true;
    else
        return false;
}
 
// Driver Program to test above function
int main()
{
    int arr[] = {1, 5, 3, 4, 2};
    int n = sizeof(arr) / sizeof(arr[0]);
    if (checkSorted(n, arr))
        cout << "Yes";
    else
        cout << "No";
    return 0;
}
 
 

Java




// Java program to check if an array
// can be sorted with at-most one swap
import java.util.Arrays;
 
class GFG
{
static boolean checkSorted(int n, int arr[])
{
    // Create a sorted copy of original array
    int []b = new int[n];
    for (int i = 0; i < n; i++)
        b[i] = arr[i];
    Arrays.sort(b, 0, n);
 
    // Check if 0 or 1 swap required to
    // get the sorted array
    int ct = 0;
    for (int i = 0; i < n; i++)
        if (arr[i] != b[i])
            ct++;
    if (ct == 0 || ct == 2)
        return true;
    else
        return false;
}
 
// Driver Code
public static void main(String[] args)
{
    int arr[] = {1, 5, 3, 4, 2};
    int n = arr.length;
    if (checkSorted(n, arr))
        System.out.println("Yes");
    else
        System.out.println("No");
}
}
 
// This code is contributed by 29AjayKumar
 
 

Python 3




# A linear Python 3 program to check
# if array becomes sorted after one swap
 
def checkSorted(n, arr):
     
    # Create a sorted copy of
    # original array
    b = []
    for i in range(n):
        b.append(arr[i])
         
    b.sort()
     
    # Check if 0 or 1 swap required
    # to get the sorted array
    ct = 0
    for i in range(n):
        if arr[i] != b[i]:
            ct += 1
             
    if ct == 0 or ct == 2:
        return True
    else:
        return False
 
# Driver Code       
if __name__ == '__main__':
     
    arr = [1, 5, 3, 4, 2]
    n = len(arr)
     
    if checkSorted(n, arr):
        print("Yes")
         
    else:
        print("No")
 
# This code is contributed
# by Rituraj Jain
 
 

C#




// C# program to check if an array
// can be sorted with at-most one swap
using System;
 
class GFG
{
static Boolean checkSorted(int n, int []arr)
{
    // Create a sorted copy of original array
    int []b = new int[n];
    for (int i = 0; i < n; i++)
        b[i] = arr[i];
    Array.Sort(b, 0, n);
 
    // Check if 0 or 1 swap required to
    // get the sorted array
    int ct = 0;
    for (int i = 0; i < n; i++)
        if (arr[i] != b[i])
            ct++;
    if (ct == 0 || ct == 2)
        return true;
    else
        return false;
}
 
// Driver Code
public static void Main(String[] args)
{
    int []arr = {1, 5, 3, 4, 2};
    int n = arr.Length;
    if (checkSorted(n, arr))
        Console.WriteLine("Yes");
    else
        Console.WriteLine("No");
}
}
 
// This code is contributed by 29AjayKumar
 
 

Javascript




<script>
// javascript program to check if an array can be sorted
// with at-most one swap
function checkSorted(n, arr)
{
 
    // Create a sorted copy of original array
    var b = Array(n).fill(0);
    for (var i = 0; i < n; i++)
        b[i] = arr[i];
    b.sort();
 
    // Check if 0 or 1 swap required to
    // get the sorted array
    var ct = 0;
    for (var i = 0; i < n; i++)
        if (arr[i] != b[i])
            ct++;
    if (ct == 0 || ct == 2)
        return true;
    else
        return false;
}
 
// Driver Program to test above function
var arr = [ 1, 5, 3, 4, 2 ];
var n = arr.length;
if (checkSorted(n, arr))
    document.write( "Yes");
else
    document.write("No");
 
// This code is contributed by noob2000.
</script>
 
 
Output
Yes

Time Complexity: O(n Log n)

Space Complexity: O(n) where n is size of input array arr. This is because array b has been created in checkSorted function.

An efficient solution is to check in linear time. Let us consider different cases that may appear after one swap. 

  1. We swap adjacent elements. For example {1, 2, 3, 4, 5} becomes {1, 2, 4, 3, 5}
  2. We swap non-adjacent elements. For example {1, 2, 3, 4, 5} becomes {1, 5, 3, 4, 2}

We traverse the given array. For every element, we check if it is smaller than the previous element. We count such occurrences. If the count of such occurrences is more than 2, then we cannot sort the array with one swap. If the count is one, we can find elements to swap (smaller and its previous). 
If the count is two, we can find elements to swap (previous of first smaller and second smaller). 

After swapping, we again check if the array becomes sorted or not. We check this to handle cases like {4, 1, 2, 3}

Implementation:

C++




// A linear CPP program to check if array becomes
// sorted after one swap
#include <bits/stdc++.h>
using namespace std;
 
int checkSorted(int n, int arr[])
{
    // Find counts and positions of
    // elements that are out of order.
    int first = 0, second = 0;
    int count = 0;
    for (int i = 1; i < n; i++) {
        if (arr[i] < arr[i - 1]) {
            count++;
            if (first == 0)
                first = i;
            else
                second = i;
        }
    }
 
    // If there are more than two elements
    // are out of order.
    if (count > 2)
        return false;
 
    // If all elements are sorted already
    if (count == 0)
        return true;
 
    // Cases like {1, 5, 3, 4, 2}
    // We swap 5 and 2.
    if (count == 2)
        swap(arr[first - 1], arr[second]);
 
    // Cases like {1, 2, 4, 3, 5}
    else if (count == 1)
        swap(arr[first - 1], arr[first]);
 
    // Now check if array becomes sorted
    // for cases like {4, 1, 2, 3}
    for (int i = 1; i < n; i++)
        if (arr[i] < arr[i - 1])
            return false;
 
    return true;
}
 
// Driver Program to test above function
int main()
{
    int arr[] = { 1, 4, 3, 2 };
    int n = sizeof(arr) / sizeof(arr[0]);
    if (checkSorted(n, arr))
        cout << "Yes";
    else
        cout << "No";
    return 0;
}
 
 

Java




// A linear Java program to check if
// array becomes sorted after one swap
class GFG
{
static boolean checkSorted(int n, int arr[])
{
    // Find counts and positions of
    // elements that are out of order.
    int first = 0, second = 0;
    int count = 0;
    for (int i = 1; i < n; i++)
    {
        if (arr[i] < arr[i - 1])
        {
            count++;
            if (first == 0)
                first = i;
            else
                second = i;
        }
    }
 
    // If there are more than two elements
    // are out of order.
    if (count > 2)
        return false;
 
    // If all elements are sorted already
    if (count == 0)
        return true;
 
    // Cases like {1, 5, 3, 4, 2}
    // We swap 5 and 2.
    if (count == 2)
        swap(arr, first - 1, second);
 
    // Cases like {1, 2, 4, 3, 5}
    else if (count == 1)
        swap(arr, first - 1, first);
 
    // Now check if array becomes sorted
    // for cases like {4, 1, 2, 3}
    for (int i = 1; i < n; i++)
        if (arr[i] < arr[i - 1])
            return false;
 
    return true;
}
 
static int[] swap(int []arr, int i, int j)
{
    int temp = arr[i];
    arr[i] = arr[j];
    arr[j] = temp;
    return arr;
}
 
// Driver Code
public static void main(String[] args)
{
    int arr[] = { 1, 4, 3, 2 };
    int n = arr.length;
    if (checkSorted(n, arr))
        System.out.println("Yes");
    else
        System.out.println("No");
}
}
 
// This code is contributed by Rajput-Ji
 
 

Python 3




# A linear Python 3 program to check
# if array becomes sorted after one swap
 
def checkSorted(n, arr):
     
    # Find counts and positions of
    # elements that are out of order.
    first, second = 0, 0
    count = 0
     
    for i in range(1, n):
        if arr[i] < arr[i - 1]:
            count += 1
             
            if first == 0:
                first = i
            else:
                second = i
     
    # If there are more than two elements
    # which are out of order.
    if count > 2:
        return False
 
    # If all elements are sorted already
    if count == 0:
        return True
 
    # Cases like {1, 5, 3, 4, 2}
    # We swap 5 and 2.
    if count == 2:
        (arr[first - 1],
         arr[second]) = (arr[second], 
                         arr[first - 1])
 
    # Cases like {1, 2, 4, 3, 5}
    elif count == 1:
        (arr[first - 1],
         arr[first]) = (arr[first],
                        arr[first - 1])
 
    # Now check if array becomes sorted
    # for cases like {4, 1, 2, 3}
    for i in range(1, n):
        if arr[i] < arr[i - 1]:
            return False
 
    return True
 
# Driver Code
if __name__ == '__main__':
     
    arr = [1, 4, 3, 2]
    n = len(arr)
     
    if checkSorted(n, arr):
        print("Yes")
         
    else:
        print("No")
 
# This code is contributed
# by Rituraj Jain
 
 

C#




// A linear C# program to check if
// array becomes sorted after one swap
using System;
 
class GFG
{
static bool checkSorted(int n, int []arr)
{
    // Find counts and positions of
    // elements that are out of order.
    int first = 0, second = 0;
    int count = 0;
    for (int i = 1; i < n; i++)
    {
        if (arr[i] < arr[i - 1])
        {
            count++;
            if (first == 0)
                first = i;
            else
                second = i;
        }
    }
 
    // If there are more than two elements
    // are out of order.
    if (count > 2)
        return false;
 
    // If all elements are sorted already
    if (count == 0)
        return true;
 
    // Cases like {1, 5, 3, 4, 2}
    // We swap 5 and 2.
    if (count == 2)
        swap(arr, first - 1, second);
 
    // Cases like {1, 2, 4, 3, 5}
    else if (count == 1)
        swap(arr, first - 1, first);
 
    // Now check if array becomes sorted
    // for cases like {4, 1, 2, 3}
    for (int i = 1; i < n; i++)
        if (arr[i] < arr[i - 1])
            return false;
 
    return true;
}
 
static int[] swap(int []arr, int i, int j)
{
    int temp = arr[i];
    arr[i] = arr[j];
    arr[j] = temp;
    return arr;
}
 
// Driver Code
public static void Main(String[] args)
{
    int []arr = { 1, 4, 3, 2 };
    int n = arr.Length;
    if (checkSorted(n, arr))
        Console.WriteLine("Yes");
    else
        Console.WriteLine("No");
}
}
 
// This code is contributed by Rajput-Ji
 
 

Javascript




<script>
 
// A linear Javascript program to check if array becomes
// sorted after one swap
 
function checkSorted(n, arr)
{
    // Find counts and positions of
    // elements that are out of order.
    var first = 0, second = 0;
    var count = 0;
    for (var i = 1; i < n; i++) {
        if (arr[i] < arr[i - 1]) {
            count++;
            if (first == 0)
                first = i;
            else
                second = i;
        }
    }
 
    // If there are more than two elements
    // are out of order.
    if (count > 2)
        return false;
 
    // If all elements are sorted already
    if (count == 0)
        return true;
 
    // Cases like {1, 5, 3, 4, 2}
    // We swap 5 and 2.
    if (count == 2)
        [arr[first - 1], arr[second]] = [arr[second], arr[first - 1]];
 
    // Cases like {1, 2, 4, 3, 5}
    else if (count == 1)
        [arr[first - 1], arr[first]] = [arr[first], arr[first - 1]];
 
    // Now check if array becomes sorted
    // for cases like {4, 1, 2, 3}
    for (var i = 1; i < n; i++)
        if (arr[i] < arr[i - 1])
            return false;
 
    return true;
}
 
// Driver Program to test above function
var arr = [1, 4, 3, 2];
var n = arr.length;
if (checkSorted(n, arr))
    document.write( "Yes");
else
    document.write( "No");
 
// This code is contributed by famously.
</script>
 
 
Output
Yes

Time Complexity: O(n)

Space Complexity: O(1) as no extra space has been used.

Exercise: How to check if an array can be sorted with two swaps?



Next Article
Check if an Array is Sorted

A

Abdullah Aslam
Improve
Article Tags :
  • Arrays
  • DSA
  • Searching
  • Sorting
  • Arrays
  • Sorting Quiz
Practice Tags :
  • Arrays
  • Arrays
  • Searching
  • Sorting

Similar Reads

  • Check if the array can be sorted using swaps between given indices only
    Given an array arr[] of size N consisting of distinct integers from range [0, N - 1] arranged in a random order. Also given a few pairs where each pair denotes the indices where the elements of the array can be swapped. There is no limit on the number of swaps allowed. The task is to find if it is p
    15+ min read
  • Check whether we can sort two arrays by swapping A[i] and B[i]
    Given two arrays, we have to check whether we can sort two arrays in strictly ascending order by swapping A[i] and B[i]. Examples: Input : A[ ]={ 1, 4, 3, 5, 7}, B[ ]={ 2, 2, 5, 8, 9} Output : True After swapping A[1] and B[1], both the arrays are sorted. Input : A[ ]={ 1, 4, 5, 5, 7}, B[ ]={ 2, 2,
    12 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
  • Check if reversing a sub array make the array sorted
    Given an array of n distinct integers. The task is to check whether reversing any one sub-array can make the array sorted or not. If the array is already sorted or can be made sorted by reversing any one subarray, print "Yes", else print "No". Examples: Input : arr [] = {1, 2, 5, 4, 3}Output : YesBy
    15+ min read
  • Check if an Array is Sorted
    Given an array of size n, the task is to check if it is sorted in ascending order or not. Equal values are allowed in an array and two consecutive equal values are considered sorted. Examples: Input: arr[] = [20, 21, 45, 89, 89, 90]Output: YesInput: arr[] = [20, 20, 45, 89, 89, 90]Output: YesInput:
    9 min read
  • Check if Array can be sorted by swapping adjacent elements having odd sum
    Given an array arr[], the task is to check if the array can be sorted using the given operation any number of times. In one operation, you can swap any two adjacent elements if their sum is odd. Examples: Input: arr[] = [1, 6, 31, 14]Output: YesExplanation: Swap 31 and 14 (31 + 14 = 45 which is odd)
    7 min read
  • Check if an array of pairs can be sorted by swapping pairs with different first elements
    Given an array arr[] consisting of N pairs, where each pair represents the value and ID respectively, the task is to check if it is possible to sort the array by the first element by swapping only pairs having different IDs. If it is possible to sort, then print "Yes". Otherwise, print "No". Example
    11 min read
  • Check if array can be sorted by swapping adjacent elements of opposite parity
    Given an array A of size n, the task is to check if the array can be sorted in increasing order, if the only operation allowed is swapping the adjacent elements if they are of opposite parity. The operation can be done any number of times. Examples: Input : n = 4, A = [1, 6, 51, 16]Output: YESExplan
    9 min read
  • Check if an array is stack sortable
    Given an array arr[] of n distinct elements, where each element is between 1 and n (inclusive), determine if it is stack-sortable.Note: An array a[] is considered stack-sortable if it can be rearranged into a sorted array b[] using a temporary stack stk with the following operations: Remove the firs
    6 min read
  • Check if a decreasing Array can be sorted using Triple cyclic shift
    Given an arr[] of size N whose elements are sorted in descending order. The task is to find if the given array can be sorted in ascending order by performing a minimum number of triple cyclic right swaps. Print the indexes involved in each of the triple cyclic right swap. Triple Cyclic Right Swap re
    8 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences