QuickSort in Java: A Fast and Efficient Sorting Algorithm

Introduction

In this article, we will explore how QuickSort works and implement it in Java. QuickSort is one of the most popular and efficient sorting algorithms used in computer science. It's known for its speed and is widely used in various programming languages, including Java.

Working of QuickSort

QuickSort is a divide-and-conquer algorithm that follows these steps:

  1. Choose a pivot element from the array.
  2. Partition the array around the pivot, moving smaller elements to the left and larger elements to the right.
  3. Recursively apply the above steps to the sub-arrays on the left and right of the pivot.

Flow Diagram

Let's implement QuickSort in Java:

public class QuickSortExample {
    public static void quickSort(int[] arr, int low, int high) {
        if (low < high) {
            int pivotIndex = partition(arr, low, high);
            quickSort(arr, low, pivotIndex - 1);
            quickSort(arr, pivotIndex + 1, high);
        }
    }

    private static int partition(int[] arr, int low, int high) {
        int pivot = arr[high];
        int i = low - 1;

        for (int j = low; j < high; j++) {
            if (arr[j] <= pivot) {
                i++;
                swap(arr, i, j);
            }
        }

        swap(arr, i + 1, high);
        return i + 1;
    }

    private static void swap(int[] arr, int i, int j) {
        int temp = arr[i];
        arr[i] = arr[j];
        arr[j] = temp;
    }

    public static void main(String[] args) {
        int[] arr = {64, 34, 25, 12, 22, 11, 90};
        System.out.println("Unsorted array: " + Arrays.toString(arr));

        quickSort(arr, 0, arr.length - 1);

        System.out.println("Sorted array: " + Arrays.toString(arr));
    }
}

Explanation of the above example

  1. The quickSort method is the main entry point for the algorithm. It checks if the sub-array has more than one element and calls the partition method to get the pivot index.
  2. The partition method chooses the last element as the pivot and places it in its correct position in the sorted array. It also places all smaller elements to the left of the pivot and all greater elements to the right.
  3. The swap method is a utility function to swap two elements in the array.
  4. In the main method, we create a sample array, print it, sort it using QuickSort, and then print the sorted array.

Time Complexity

  • Best and Average case: O(n log n)
  • Worst case: O(n^2) (rare, occurs when the pivot is always the smallest or largest element)

Space Complexity: O(log n) due to the recursive calls.

Summary

QuickSort is a powerful and efficient sorting algorithm that's widely used in practice. Its implementation in Java is straightforward and can be easily adapted for different types of data. Understanding QuickSort is essential for any programmer dealing with sorting and searching problems.


Similar Articles