Sorting Algorithms

Index

  1. Time Complexities
  2. Selection sort
  3. Bubble sort
  4. Insertion sort
  5. Quick Sort sort
  6. Merge Sort sort
  7. Heap sort

Time-Complexity of Sorting-Algorithms

ALGORITHMWORST-case Time Complexity(Big O Notation)AVERAGE-case time complexity (Theta Notation)BEST-case time-complexity (Omega Notation)
Selection sortingO(n^2)θ(n^2)Ω(n^2)
Bubble sortingO(n^2)θ(n^2)Ω(n)
Insertion sortingO(n^2)θ(n^2)Ω(n)
Heap sortingO(nlog(n))θΩ
Quick sortingO(n^2)θΩ
Merge sortingO(nlog(n))θΩ
Bucket sortingO(n^2)θΩ
Radix sortingO(nk)θΩ
Tree-sort O(nlog(n))

Working of Sorting Algorithms


Usage : Selection vs Insertion vs Bubble sort

  1. Selection Sort is best when memory write operations are costly since it makes the minimum possible number of swaps compared to other two.
  2. Insertion Sort is preferable for small or nearly sorted data.
  3. Bubble Sort is typically used for educational purposes to demonstrate sorting techniques but is rarely used in practical applications due to its inefficiency.

Selection Sorting


Algorithm :

  1. Iterate through the array to find the smallest (or largest) element.
  2. Swap the found minimum (or maximum) element with the first element.
  3. Move the boundary of the unsorted subarray by one element.
  4. Repeat the process for the remaining unsorted portion of the array.

  private static void selectionSort(int[] arr) {
        int n = arr.length;
        for (int i = 0; i < n; i++) {
            int minIndex = i;
            for (int j = i + 1; j < n; j++) {
                if (arr[j] < arr[minIndex]) {
                    minIndex = j;
                }
            }
//optimisation used :  outer loop used for swapping - internal for index tracking
            int temp = arr[minIndex];
            arr[minIndex] = arr[i];
            arr[i] = temp;

        }
    }
  1. Time Complexity: O(n²)
  2. Space Complexity: O(1) (In-place sorting)

Bubble Sort

Algorithm :

  1. Compare adjacent elements in the array.
  2. Swap them if they are in the wrong order.
  3. Continue doing this for each pair of adjacent elements until the array is fully sorted
  4. .After each pass, the next largest element is in its correct position.
  5. Repeat the process until no swaps are needed (the array is sorted).

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

            for (int j = 0; j < n - 1; j++) {
                if(arr[j]>arr[j+1]){
                    int temp=arr[j+1];
                    arr[j+1]=arr[j];
                    arr[j]=temp;
                }
            }
        }
     
    }
  1. Time Complexity: O(n²)
  2. Space Complexity: O(1) (In-place sorting)

Insertion Sort

Algorithm :

  1. Start from the second element, assume that the first element is already sorted.
  2. Pick the next element and compare it with the elements in the sorted part.
  3. Shift all elements in the sorted part that are greater than the current element to the right.
  4. Insert the current element into its correct position.
  5. Repeat the process until the entire array is sorted.

 public 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
            while (j >= 0 && arr[j] > key) {
                arr[j + 1] = arr[j];
                j = j - 1;
            }
            arr[j + 1] = key;
        }
    }
  1. Time Complexity: O(n²)
  2. Space Complexity: O(1) (In-place sorting)

Quick Sort

Algorithm :

  1. Choose a “pivot” element from the array.
  2. Partition the array into two sub-arrays: elements less than the pivot and elements greater than the pivot.
  3. Recursively apply the same steps to the sub-arrays.
  4. Combine the sub-arrays to get the sorted array.
  public static void quickSort(int[] arr, int low, int high) {
        if (low < high) {
            int pi = partition(arr, low, high);
            quickSort(arr, low, pi - 1);  // Recursively sort elements before partition
            quickSort(arr, pi + 1, high); // Recursively sort elements after partition
        }
    }

    private static int partition(int[] arr, int low, int high) {
        int pivot = arr[high];
        int i = (low - 1); // Index of smaller element
        for (int j = low; j < high; j++) {
            if (arr[j] < pivot) {
                i++;
                // Swap arr[i] and arr[j]
                int temp = arr[i];
                arr[i] = arr[j];
                arr[j] = temp;
            }
        }
        // Swap arr[i+1] and arr[high] (or pivot)
        int temp = arr[i + 1];
        arr[i + 1] = arr[high];
        arr[high] = temp;

        return i + 1;
    }
  1. Time Complexity:
    • Best Case: O(n log n)
    • Worst Case: O(n²) (occurs when the smallest or largest element is always chosen as the pivot)
  2. Space Complexity: O(log n) (in-place sorting, though recursion stack takes

Merge Sort

Algorithm :

  1. Divide the array into two halves.
  2. Recursively sort each half.
  3. Merge the two halves to create a sorted array.
public class MergeSort {
    public static void mergeSort(int[] arr, int left, int right) {
        if (left < right) {
            int middle = (left + right) / 2;
            // Sort first and second halves
            mergeSort(arr, left, middle);
            mergeSort(arr, middle + 1, right);
            // Merge the sorted halves
            merge(arr, left, middle, right);
        }
    }

    private static void merge(int[] arr, int left, int middle, int right) {
        int n1 = middle - left + 1;
        int n2 = right - middle;

        // Temporary arrays
        int[] L = new int[n1];
        int[] R = new int[n2];

        // Copy data to temp arrays
        for (int i = 0; i < n1; i++)
            L[i] = arr[left + i];
        for (int j = 0; j < n2; j++)
            R[j] = arr[middle + 1 + j];

        // Merge the temp arrays
        int i = 0, j = 0;
        int k = left;
        while (i < n1 && j < n2) {
            if (L[i] <= R[j]) {
                arr[k] = L[i];
                i++;
            } else {
                arr[k] = R[j];
                j++;
            }
            k++;
        }

        // Copy remaining elements of L[]
        while (i < n1) {
            arr[k] = L[i];
            i++;
            k++;
        }

        // Copy remaining elements of R[]
        while (j < n2) {
            arr[k] = R[j];
            j++;
            k++;
        }
    }

    public static void main(String[] args) {
        int[] arr = {12, 11, 13, 5, 6, 7};
        
        // Call mergeSort with the full range of the array
        mergeSort(arr, 0, arr.length - 1);
        
        // Print the sorted array
        System.out.println("Sorted array:");
        for (int num : arr) {
            System.out.print(num + " ");
        }
    }
}


Heap sort


Algorithm :


Published by

Unknown's avatar

sevanand yadav

software engineer working as web developer having specialization in spring MVC with mysql,hibernate

Leave a comment