Open In App

Introduction to Exchange Sort Algorithm

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:

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




// 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 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.




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# 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.




// 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++ 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;
}




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] + " ");
        }
    }
}




# 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=" ")




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] + " ");
        }
    }
}




// 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:


Article Tags :