Open In App

Introduction to Exchange Sort Algorithm

Improve
Improve
Like Article
Like
Save
Share
Report

Exchange sort is an algorithm used to sort in ascending as well as descending order. It compares the first element with every element if any element seems out of order it swaps.

Example:

Input: arr[] = {5, 1, 4, 2, 8}
Output: {1, 2, 4, 5, 8}
Explanation: Working of exchange sort:

  • 1st Pass
    Exchange sort starts with the very first elements, comparing with other elements to check which one is greater.
    ( 5 1 4 2 8 ) –> ( 1 5 4 2 8 ).
    Here, the algorithm compares the first two elements and swaps since 5 > 1
    No swap since none of the elements is smaller than 1 so after 1st iteration (1 5 4 2 8
  • 2nd Pass:
    (1 5 4 2 8 ) –>  ( 1 4 5 2 8 ), since 4 < 5
    ( 1 4 5 2 8 ) –> ( 1 2 5 4 8 ), since 2 < 4
    ( 1 2 5 4 8 ) No change since in this there is no other element smaller than 2
  • 3rd Pass:
    (1 2 5 4 8 ) -> (1 2 4 5 8 ), since 4 < 5
    after completion of the iteration, we found array is sorted
  • After completing the iteration it will come out of the loop, Therefore array is sorted.

To sort in Ascending order:

procedure ExchangeSort(num: list of sortable items)
  n = length(A)

  // outer loop
  for i = 1 to n – 2 do

  // inner loop

      for j = i + 1 to n-1 do

           if num[i] > num[j] do

               swap(num[i], num[j])
           end if
       end for
   end for
end procedure

Steps Involved in Implementation for ascending order sorting:

  • First, we will iterate over the array from arr[1] to n – 2 in the outer loop to compare every single element with every other element in an array, inner loops will take of comparing that single element in the outer loop with all the other elements in an array. 
  • The inner loop will start from i + 1st index where i is the index of the outer loop
  • We compare if the ith element is bigger than the jth element we swap in case of ascending order
  • To sort in descending order we swap array elements if the jth element is bigger than the ith element 
  • If there is no case where the condition doesn’t meet that means it is already in desired order so we won’t perform any operations 
  • Here both if and the inner loop end and so does the outer loop after that we didn’t take the last element in the outer loop since the inner loop’s current index is i+1th so eventually, when the current index of the outer loop is n-2 it will automatically take care of last element due to i+1th index of the inner loop. this case can also be considered a corner case for this algorithm

Below is the code to sort the array into ascending order:

C++




// C++ implementation of the above approach
#include <bits/stdc++.h>
using namespace std;
 
// Function for Exchange sort in Ascending order
void exchangeSort(int num[], int size)
{
 
    int i, j, temp;
    for (i = 0; i < size - 1; i++) {
        // Outer Loop
        for (j = i + 1; j < size; j++) {
            // Inner Loop
            // Sorting into ascending order if
            // previous element bigger than next
            // element we swap to make it in ascending order
            if (num[i] > num[j]) {
 
                // Swapping
                temp = num[i];
                num[i] = num[j];
                num[j] = temp;
            }
        }
    }
}
 
// Driver code
int main()
{
 
    int arr[5] = { 5, 1, 4, 2, 8 };
 
    // Function call
    exchangeSort(arr, 5);
    for (int i = 0; i < 5; i++) {
        cout << arr[i] << " ";
    }
    return 0;
}


Java




// Java implementation of the above approach
import java.io.*;
import java.util.*;
 
class GFG {
 
  // Function for Exchange sort in Ascending order
  static void exchangeSort(int[] num, int size)
  {
    int i, j, temp;
    for (i = 0; i < size - 1; i++)
    {
       
      // Outer Loop
      for (j = i + 1; j < size; j++)
      {
         
        // Inner Loop
        // Sorting into ascending order if previous
        // element bigger than next element we swap
        // to make it in ascending order
        if (num[i] > num[j])
        {
           
          // Swapping
          temp = num[i];
          num[i] = num[j];
          num[j] = temp;
        }
      }
    }
  }
 
  public static void main(String[] args)
  {
    int[] arr = { 5, 1, 4, 2, 8 };
 
    // Function call
    exchangeSort(arr, 5);
    for (int i : arr) {
      System.out.print(i + " ");
    }
  }
}
 
// This code is contributed by sankar.


Python3




def exchange_sort(num):
    size = len(num)
    for i in range(size - 1):
        # Outer Loop
        for j in range(i + 1, size):
            # Inner Loop
            # Sorting into ascending order if
            # previous element bigger than next
            # element we swap to make it in ascending order
            if num[i] > num[j]:
                # Swapping
                num[i], num[j] = num[j], num[i]
 
# Driver code
if __name__ == "__main__":
    arr = [5, 1, 4, 2, 8]
 
    # Function call
    exchange_sort(arr)
    for i in range(len(arr)):
        print(arr[i], end=" ")


C#




// C# implementation of the above approach
 
using System;
 
public class GFG {
 
    // Function for Exchange sort in Ascending order
    static void exchangeSort(int[] num, int size)
    {
        int i, j, temp;
        for (i = 0; i < size - 1; i++) {
 
            // Outer Loop
            for (j = i + 1; j < size; j++) {
 
                // Inner Loop
                // Sorting into ascending order if previous
                // element bigger than next element we swap
                // to make it in ascending order
                if (num[i] > num[j]) {
 
                    // Swapping
                    temp = num[i];
                    num[i] = num[j];
                    num[j] = temp;
                }
            }
        }
    }
 
    static public void Main()
    {
 
        // Code
        int[] arr = { 5, 1, 4, 2, 8 };
 
        // Function call
        exchangeSort(arr, 5);
        foreach(int i in arr) { Console.Write(i + " "); }
    }
}
 
// This code is contributed by lokesh.


Javascript




// Function for Exchange sort in Ascending order
function exchangeSort(arr) {
    const size = arr.length;
 
    for (let i = 0; i < size - 1; i++) {
        // Outer Loop
        for (let j = i + 1; j < size; j++) {
            // Inner Loop
            // Sorting into ascending order if
            // the previous element is bigger than the next
            // element; we swap to make it in ascending order
            if (arr[i] > arr[j]) {
                // Swapping
                const temp = arr[i];
                arr[i] = arr[j];
                arr[j] = temp;
            }
        }
    }
}
 
// Driver code
const arr = [5, 1, 4, 2, 8];
 
// Function call
exchangeSort(arr);
 
// Output the sorted array
console.log(arr.join(' '));


Output

1 2 4 5 8 









Time Complexity: O(N^2)
Auxiliary Space : O(1)

To sort in Descending order:

procedure ExchangeSort(num: list of sortable items)
n = length(A)

  //outer loop
  for i = 1 to n – 2 do

  //inner loop.

      for j = i + 1 to n-1 do

           if num[i] < num[j] do

               swap(num[i], num[j])
           end if
       end for
   end for
end procedure

Below is the code to sort the array into Descending order:

C++




// C++ code for the above approach
#include <bits/stdc++.h>
using namespace std;
 
// Function for Exchange sort
// in Descending order
void exchangeSort(int num[], int size)
{
    int i, j, temp;
    for (i = 0; i < size - 1; i++) {
        for (j = i + 1; j < size; j++) {
 
            // Sorting into descending
            // order when previous element
            // is smaller than next element
            if (num[i] < num[j]) {
 
                // Swapping
                temp = num[i];
                num[i] = num[j];
                num[j] = temp;
            }
        }
    }
}
 
// Driver code
int main()
{
    int arr[5] = { 5, 1, 4, 2, 8 };
 
    // Function call
    exchangeSort(arr, 5);
 
    for (int i = 0; i < 5; i++) {
        cout << arr[i] << " ";
    }
    return 0;
}


Java




import java.util.Arrays;
 
public class ExchangeSort {
     
    // Function for Exchange sort in Descending order
    static void exchangeSort(int[] num) {
        int size = num.length;
        int temp;
 
        for (int i = 0; i < size - 1; i++) {
            for (int j = i + 1; j < size; j++) {
 
                // Sorting into descending order when previous element
                // is smaller than the next element
                if (num[i] < num[j]) {
 
                    // Swapping
                    temp = num[i];
                    num[i] = num[j];
                    num[j] = temp;
                }
            }
        }
    }
 
    // Driver code
    public static void main(String[] args) {
        int[] arr = { 5, 1, 4, 2, 8 };
 
        // Function call
        exchangeSort(arr);
 
        // Printing the sorted array
        for (int i = 0; i < arr.length; i++) {
            System.out.print(arr[i] + " ");
        }
    }
}


Python3




# Python code for the above approach
 
# Function for Exchange sort
# in Descending order
def exchange_sort(arr):
    size = len(arr)
    for i in range(size - 1):
        for j in range(i + 1, size):
 
            # Sorting into descending
            # order when previous element
            # is smaller than next element
            if arr[i] < arr[j]:
 
                # Swapping
                arr[i], arr[j] = arr[j], arr[i]
 
# Driver code
if __name__ == "__main__":
    arr = [5, 1, 4, 2, 8]
 
    # Function call
    exchange_sort(arr)
 
    for num in arr:
        print(num, end=" ")


C#




using System;
 
class Program {
    // Function for Exchange sort
    // in Descending order
    static void ExchangeSort(int[] num, int size)
    {
        int i, j, temp;
        for (i = 0; i < size - 1; i++) {
            for (j = i + 1; j < size; j++) {
                // Sorting into descending
                // order when previous element
                // is smaller than next element
                if (num[i] < num[j]) {
                    // Swapping
                    temp = num[i];
                    num[i] = num[j];
                    num[j] = temp;
                }
            }
        }
    }
 
    // Driver code
    static void Main()
    {
        int[] arr = { 5, 1, 4, 2, 8 };
 
        // Function call
        ExchangeSort(arr, 5);
 
        // Printing the sorted array
        for (int i = 0; i < 5; i++) {
            Console.Write(arr[i] + " ");
        }
    }
}


Javascript




// Function for Exchange sort in Descending order
function exchangeSort(num) {
    let size = num.length;
    let temp;
 
    for (let i = 0; i < size - 1; i++) {
        for (let j = i + 1; j < size; j++) {
 
            // Sorting into descending order when previous element
            // is smaller than the next element
            if (num[i] < num[j]) {
 
                // Swapping
                temp = num[i];
                num[i] = num[j];
                num[j] = temp;
            }
        }
    }
}
 
// Driver code
let arr = [5, 1, 4, 2, 8];
 
// Function call
exchangeSort(arr);
 
// Printing the sorted array
for (let i = 0; i < arr.length; i++) {
    console.log(arr[i] + " ");
}


Output

8 5 4 2 1 

Time Complexity: O(N^2)
Auxiliary Space : O(1)

Advantages of using Exchange sort over other sorting methods:

  • There are some situations where exchange sort may be preferable over other algorithms. For example, exchange sort may be useful when sorting very small arrays or when sorting data that is already mostly sorted. In these cases, the overhead of implementing a more complex algorithm may not be worth the potential performance gains.
  • Another advantage of the exchange sort is that it is stable, meaning that it preserves the relative order of equal elements. This can be important in some applications, such as when sorting records that contain multiple fields.


Last Updated : 15 Jan, 2024
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads