Introduction to Sorting Techniques (original) (raw)

Last Updated : 12 May, 2026

**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 Important

Sorting algorithms are essential in Computer Science as they simplify complex problems and improve efficiency. They are widely used in searching, databases, divide and conquer strategies, and data structures.

Key Applications:

Sorting Basics

Types of Sorting Techniques

There are various sorting algorithms are used in data structures. The following two types of sorting algorithms can be broadly classified:

  1. **Comparison-based: We compare the elements in a comparison-based sorting algorithm)
  2. **Non-comparison-based: We do not compare the elements in a non-comparison-based sorting algorithm)

Sorting algorithm

Sorting algorithm

Basics Sorting Algorithms:

Bubble Sort - O(n^2) Time and O(1) Space

It is a simple sorting algorithm that repeatedly swaps adjacent elements if they are in the wrong order. It performs multiple passes through the array, and in each pass, the largest unsorted element moves to its correct position at the end.

After each pass, we ignore the last sorted elements and continue comparing and swapping remaining adjacent pairs. After k passes, the last k elements are sorted. For more details refer here.

C++ `

#include #include using namespace std;

// An optimized version of Bubble Sort void bubbleSort(vector& arr) { int n = arr.size(); bool swapped;

for (int i = 0; i < n - 1; i++) {
    swapped = false;
    for (int j = 0; j < n - i - 1; j++) {
        if (arr[j] > arr[j + 1]) {
            swap(arr[j], arr[j + 1]);
            swapped = true;
        }
    }
  
    // If no two elements were swapped, then break
    if (!swapped)
        break;
}

}

int main() { vector arr = { 5, 6, 1, 3 }; bubbleSort(arr); for (int num : arr) cout << num << " "; }

Java

// Optimized java implementation of Bubble sort

class GFG {

// An optimized version of Bubble Sort
static void bubbleSort(int arr[], int n){
    int i, j, temp;
    boolean swapped;
    for (i = 0; i < n - 1; i++) {
        swapped = false;
        for (j = 0; j < n - i - 1; j++) {
            if (arr[j] > arr[j + 1]) {
                
                // Swap arr[j] and arr[j+1]
                temp = arr[j];
                arr[j] = arr[j + 1];
                arr[j + 1] = temp;
                swapped = true;
            }
        }

        // If no two elements were
        // swapped by inner loop, then break
        if (swapped == false)
            break;
    }
}

public static void main(String args[]){
    int arr[] = { 5, 6, 1, 3 };
    int n = arr.length;
    bubbleSort(arr, n);
    for (int i = 0; i < n; i++)
        System.out.print(arr[i] + " ");
}

}

Python

Optimized Python program for implementation of Bubble Sort

def bubbleSort(arr): n = len(arr)

# Traverse through all array elements
for i in range(n):
    swapped = False

    # Last i elements are already in place
    for j in range(0, n-i-1):

        # Traverse the array from 0 to n-i-1
        # Swap if the element found is greater
        # than the next element
        if arr[j] > arr[j+1]:
            arr[j], arr[j+1] = arr[j+1], arr[j]
            swapped = True
    if (swapped == False):
        break

if name == "main": arr = [5, 6, 1, 3]

bubbleSort(arr)
for i in range(len(arr)):
    print("%d" % arr[i], end=" ")

C#

// Optimized C# implementation of Bubble sort using System;

class GFG {

static void bubbleSort(int[] arr, int n){
    int i, j, temp;
    bool swapped;
    for (i = 0; i < n - 1; i++) {
        swapped = false;
        for (j = 0; j < n - i - 1; j++) {
            if (arr[j] > arr[j + 1]) {
                
                // Swap arr[j] and arr[j+1]
                temp = arr[j];
                arr[j] = arr[j + 1];
                arr[j + 1] = temp;
                swapped = true;
            }
        }

        // If no two elements were
        // swapped by inner loop, then break
        if (swapped == false)
            break;
    }
}


public static void Main(){
    int[] arr = { 5, 6, 1, 3 };
    int n = arr.Length;
    bubbleSort(arr, n);
    for (int i = 0; i < n; i++)
        Console.Write(arr[i] + " ");
}

}

JavaScript

// Optimized javaScript implementation // of Bubble sort function bubbleSort(arr){ var i, j, temp; var swapped; var n = arr.length; for (i = 0; i < n - 1; i++){ swapped = false; for (j = 0; j < n - i - 1; j++){ if (arr[j] > arr[j + 1]) { // Swap arr[j] and arr[j+1] temp = arr[j]; arr[j] = arr[j + 1]; arr[j + 1] = temp; swapped = true; } }

    // IF no two elements were 
    // swapped by inner loop, then break
    if (swapped == false)
    break;
}

}

// Driver program var arr = [5, 6, 1, 3]; bubbleSort(arr); console.log(...arr);

`

Output

11 12 22 25 34 64 90

Insertion Sort - O(n^2) Time and O(1) Space

It is a simple sorting algorithm that builds the sorted array one element at a time. It works like sorting playing cards in your hand, where each new card is inserted into its correct position among the already sorted cards.

We start with the second element, assuming the first is already sorted. If the second element is smaller, we shift the first element and insert the second in the correct position. Then we move to the third element and place it correctly among the first two. This process continues until the entire array is sorted. For more details refer here.

C++ `

#include #include using namespace std;

void insertionsort(vector& arr, int n) { for (int i = 1; i < n; ++i) { int key = arr[i]; int j = i - 1;

    // move elements greater than key one position ahead
    while (j >= 0 && arr[j] > key) {
        arr[j + 1] = arr[j];
        j--;
    }
    arr[j + 1] = key;
}

}

int main() { vector arr = {12, 11, 13, 5, 6}; int n = arr.size();

insertionsort(arr, n);

for (int i = 0; i < n; ++i)
    cout << arr[i] << " ";

return 0;

}

Java

public class GfG {

static void insertionSort(int arr[]) {
    int n = arr.length;
    for (int i = 1; i < n; ++i) {
        int key = arr[i];
        int j = i - 1;

        /* Move elements of arr[0..i-1], that are
           greater than key, to one position ahead
           of their current position */
        while (j >= 0 && arr[j] > key) {
            arr[j + 1] = arr[j];
            j = j - 1;
        }
        arr[j + 1] = key;
    }
}


public static void main(String args[]) {
    int arr[] = { 12, 11, 13, 5, 6 };

    insertionSort(arr);
    for (int i = 0; i < arr.length; ++i)
      System.out.print(arr[i] + " ");
}

}

Python

def insertionSort(arr): for i in range(1, len(arr)): key = arr[i] j = i - 1

    # Move elements of arr[0..i-1], that are
    # greater than key, to one position ahead
    # of their current position
    while j >= 0 and key < arr[j]:
        arr[j + 1] = arr[j]
        j -= 1
    arr[j + 1] = key

if name == "main": arr = [12, 11, 13, 5, 6] insertionSort(arr) for i in range(len(arr)): print(arr[i], end=" ")

C#

using System;

class GfG { public void insertionSort(int[] arr) { int n = arr.Length; for (int i = 1; i < n; ++i) { int key = arr[i]; int j = i - 1;

        /* Move elements of arr[0..i-1], that are
           greater than key, to one position ahead
           of their current position */
        while (j >= 0 && arr[j] > key) {
            arr[j + 1] = arr[j];
            j = j - 1;
        }
        arr[j + 1] = key;
    }
}

public static void Main() {
    int[] arr = { 12, 11, 13, 5, 6 };
    GfG obj = new GfG();
    obj.insertionSort(arr);
    for (int i = 0; i < arr.Length; ++i)
        Console.Write(arr[i] + " ");
}

}

JavaScript

function insertionSort(arr) { for (let i = 1; i < arr.length; i++) { let key = arr[i]; let j = i - 1;

    /* Move elements of arr[0..i-1], that are
       greater than key, to one position ahead
       of their current position */
    while (j >= 0 && arr[j] > key) {
        arr[j + 1] = arr[j];
        j = j - 1;
    }
    arr[j + 1] = key;
}

}

// Driver method let arr = [12, 11, 13, 5, 6]; insertionSort(arr); console.log(arr.join(" "));

`

Selection Sort - O(n^2) Time and O(1) Space

It is a comparison-based sorting algorithm that repeatedly selects the smallest (or largest) element from the unsorted part of the array and swaps it with the first unsorted element. This process continues until the array is fully sorted.

We start by finding the smallest element and swap it with the first element. Then we find the next smallest element among the remaining and swap it with the second element. This continues until all elements are placed in their correct positions. For more details refer here.

C++ `

#include #include using namespace std;

void selectionSort(vector &arr) { int n = arr.size();

for (int i = 0; i < n - 1; ++i) {

    // Assume the current position holds
    // the minimum element
    int min_idx = i;

    // Iterate through the unsorted portion
    // to find the actual minimum
    for (int j = i + 1; j < n; ++j) {
        if (arr[j] < arr[min_idx]) {

            // Update min_idx if a smaller
            // element is found
            min_idx = j; 
        }
    }

    // Move minimum element to its
    // correct position
    swap(arr[i], arr[min_idx]);
}

}

int main() { vector arr = {64, 25, 12, 22, 11}; selectionSort(arr);

for (int &val : arr) {
    cout << val << " ";
}

return 0;

}

Java

import java.util.Arrays;

class GfG {

static void selectionSort(int[] arr){
    int n = arr.length;
    for (int i = 0; i < n - 1; i++) {
      
        // Assume the current position holds
        // the minimum element
        int min_idx = i;

        // Iterate through the unsorted portion
        // to find the actual minimum
        for (int j = i + 1; j < n; j++) {
            if (arr[j] < arr[min_idx]) {
              
                // Update min_idx if a smaller element
                // is found
                min_idx = j;
            }
        }

        // Move minimum element to its
        // correct position
        int temp = arr[i];
        arr[i] = arr[min_idx];
        arr[min_idx] = temp;           
    }
}


public static void main(String[] args){
    int[] arr = { 64, 25, 12, 22, 11 };
    selectionSort(arr);

     for (int val : arr) {
        System.out.print(val + " ");
    }
}

}

Python

def selectionSort(arr): n = len(arr) for i in range(n - 1):

    # Assume the current position holds
    # the minimum element
    min_idx = i
    
    # Iterate through the unsorted portion
    # to find the actual minimum
    for j in range(i + 1, n):
        if arr[j] < arr[min_idx]:
          
            # Update min_idx if a smaller element is found
            min_idx = j
    
    # Move minimum element to its
    # correct position
    arr[i], arr[min_idx] = arr[min_idx], arr[i]

if name == "main": arr = [64, 25, 12, 22, 11]

selectionSort(arr)

for val in arr:
    print(val, end=" ")

C#

// C# program for implementation // of Selection Sort using System;

class GfG {

static void selectionSort(int[] arr){
    int n = arr.Length;
    for (int i = 0; i < n - 1; i++) {

        // Assume the current position holds
        // the minimum element
        int min_idx = i;

        // Iterate through the unsorted portion
        // to find the actual minimum
        for (int j = i + 1; j < n; j++) {
            if (arr[j] < arr[min_idx]) {

                // Update min_idx if a smaller element
                // is found
                min_idx = j;
            }
        }

       // Move minimum element to its
       // correct position
       int temp = arr[i];
       arr[i] = arr[min_idx];
       arr[min_idx] = temp;         
    }
}

public static void Main(){
    int[] arr = { 64, 25, 12, 22, 11 };
    selectionSort(arr);
    
    foreach(int val in arr){
        Console.Write(val + " ");
    }
}

}

JavaScript

function selectionSort(arr) { let n = arr.length; for (let i = 0; i < n - 1; i++) {

    // Assume the current position holds
    // the minimum element
    let min_idx = i;
    
    // Iterate through the unsorted portion
    // to find the actual minimum
    for (let j = i + 1; j < n; j++) {
        if (arr[j] < arr[min_idx]) {
        
            // Update min_idx if a smaller element is found
            min_idx = j;
        }
    }
    
    // Move minimum element to its
    // correct position
    let temp = arr[i];
    arr[i] = arr[min_idx];
    arr[min_idx] = temp;
}

}

// Driver function const arr = [64, 25, 12, 22, 11]; selectionSort(arr); for (let val of arr) { process.stdout.write(val + " "); }

`

Counting Sort

It is a non-comparison-based sorting algorithm that works efficiently when the range of input values is small relative to the number of elements. It counts the frequency of each distinct element and uses that count to place elements directly into their correct sorted positions.

However, if the maximum value is much larger than the array size (especially more than n log n), then standard comparison-based algorithms are usually more efficient. For more details refer here.

C++ `

#include #include using namespace std;

vector countsort(vector& arr) { int n = arr.size();

// find the maximum element
int maxval = 0;
for (int i = 0; i < n; i++)
    maxval = max(maxval, arr[i]);

// create and initialize count array
vector<int> count(maxval + 1, 0);

// count frequency of each element
for (int i = 0; i < n; i++)
    count[arr[i]]++;

// compute prefix sum
for (int i = 1; i <= maxval; i++)
    count[i] += count[i - 1];

// build output array
vector<int> ans(n);
for (int i = n - 1; i >= 0; i--) {
    ans[count[arr[i]] - 1] = arr[i];
    count[arr[i]]--;
}

return ans;

}

int main() { vector arr = {2,5,3,0,2,3,0,3}; vector sorted = countsort(arr);

for (int x : sorted)
    cout << x << " ";

return 0;

}

Java

import java.util.ArrayList;

class GfG { public static ArrayList countsort(int arr[]) { int n = arr.length;

    // find the maximum element
    int maxval = 0;
    for (int i = 0; i < n; i++)
        if (arr[i] > maxval) maxval = arr[i];

    // create and initialize count array
    int[] count = new int[maxval + 1];

    // count frequency of each element
    for (int i = 0; i < n; i++)
        count[arr[i]]++;

    // compute prefix sum
    for (int i = 1; i <= maxval; i++)
        count[i] += count[i - 1];

    // build output array
    int[] ans = new int[n];
    for (int i = n - 1; i >= 0; i--) {
        ans[count[arr[i]] - 1] = arr[i];
        count[arr[i]]--;
    }

    // convert to ArrayList
    ArrayList<Integer> result = new ArrayList<>();
    for (int x : ans)
        result.add(x);

    return result;
}

public static void main(String[] args) {
    int arr[] = {2,5,3,0,2,3,0,3};
    ArrayList<Integer> sorted = countsort(arr);

    for (int x : sorted)
        System.out.print(x + " ");
}

}

Python

def countsort(arr): n = len(arr)

# find the maximum element
maxval = max(arr)

# create and initialize count array
count = [0] * (maxval + 1)

# count frequency of each element
for num in arr:
    count[num] += 1

# compute prefix sum
for i in range(1, maxval + 1):
    count[i] += count[i - 1]

# build output array
ans = [0] * n
for i in range(n - 1, -1, -1):
    val = arr[i]
    ans[count[val] - 1] = val
    count[val] -= 1

return ans

if name == "main": arr = [2,5,3,0,2,3,0,3] sortedArr = countsort(arr) print(*sortedArr)

C#

using System; using System.Collections.Generic;

class GfG { public static List countsort(int[] arr) { int n = arr.Length;

    // find the maximum element
    int maxval = 0;
    for (int i = 0; i < n; i++)
        maxval = Math.Max(maxval, arr[i]);

    // create and initialize count array
    int[] count = new int[maxval + 1];

    // count frequency of each element
    for (int i = 0; i < n; i++)
        count[arr[i]]++;

    // compute prefix sum
    for (int i = 1; i <= maxval; i++)
        count[i] += count[i - 1];

    // build output array
    int[] ans = new int[n];
    for (int i = n - 1; i >= 0; i--) {
        int val = arr[i];
        ans[count[val] - 1] = val;
        count[val]--;
    }

    // convert to List<int>
    List<int> result = new List<int>();
    foreach (int x in ans)
        result.Add(x);

    return result;
}

static void Main() {
    int[] arr = {2,5,3,0,2,3,0,3};
    List<int> sorted = countsort(arr);

    foreach (int x in sorted)
        Console.Write(x + " ");
}

}

JavaScript

class GfG { static countsort(arr) { let n = arr.length;

    // find the maximum element
    let maxval = Math.max(...arr);

    // create and initialize count array
    let count = Array(maxval + 1).fill(0);

    // count frequency of each element
    for (let i = 0; i < n; i++)
        count[arr[i]]++;

    // compute prefix sum
    for (let i = 1; i <= maxval; i++)
        count[i] += count[i - 1];

    // build output array
    let ans = Array(n);
    for (let i = n - 1; i >= 0; i--) {
        let val = arr[i];
        ans[count[val] - 1] = val;
        count[val]--;
    }

    return ans;
}

}

// Driver code let arr = [2,5,3,0,2,3,0,3]; let sorted = GfG.countsort(arr); console.log(...sorted);

`

**Time Complexity: O(n + m), where n and m are the size of arr[]and count[]respectively
**Auxiliary Space: O(n + m)

Some of the most common sorting algorithms are:

Selection sort, Bubble sort, Insertion Sort, Cycle Sort, Merge Sort, 3-way Merge Sort, Quick sort, Heap sort and Counting sort

Some other Sorting algorithms:

Radix sort, Bucket sort, Shell sort, Tim Sort, Comb Sort, Pigeonhole sorting, Cocktail Sort, Strand sort, Bitonic Sort, Stooge Sort, Tag Sort, Tree sort, Cartesian Sort, Odd-Even Sort / Brick Sort, Gnome sort, Cocktail shaker sort

Comparison of Complexity Analysis of Sorting Algorithms:

Name Best Case Average Case Worst Case Memory Stable Method Used
Quick Sort n log n n log n n^{2} log n No Partitioning
Merge Sort n log n n log n n log n n Yes Merging
Heap Sort n log n n log n n log n 1 No Selection
Insertion Sort n n^{2} n^{2} 1 Yes Insertion
Tim Sort n n log n n log n n Yes Insertion & Merging
Selection Sort n^{2} n^{2} n^{2} 1 No Selection
Shell Sort n log n n^{4/3} n^{3/2} 1 No Insertion
Bubble Sort n n^{2} n^{2} 1 Yes Exchanging
Cycle Sort n^{2} n^{2} n^{2} 1 No Selection