Java program to implement quick sort algorithm

www.ig‮i‬ftidea.com

Here's an example Java program that implements the Quick Sort algorithm:

public class QuickSort {
  
    public static void quickSort(int[] arr, int left, int right) {
        if (left < right) {
            int pivotIndex = partition(arr, left, right);
            quickSort(arr, left, pivotIndex - 1);
            quickSort(arr, pivotIndex + 1, right);
        }
    }

    public static int partition(int[] arr, int left, int right) {
        int pivot = arr[right];
        int i = left - 1;
        for (int j = left; j < right; j++) {
            if (arr[j] < pivot) {
                i++;
                int temp = arr[i];
                arr[i] = arr[j];
                arr[j] = temp;
            }
        }
        int temp = arr[i + 1];
        arr[i + 1] = arr[right];
        arr[right] = temp;
        return i + 1;
    }

    public static void printArray(int[] arr) {
        for (int i = 0; i < arr.length; i++) {
            System.out.print(arr[i] + " ");
        }
        System.out.println();
    }

    public static void main(String[] args) {
        int[] arr = { 9, 4, 6, 8, 7, 5, 2, 1, 3 };
        System.out.println("Before sorting:");
        printArray(arr);
        quickSort(arr, 0, arr.length - 1);
        System.out.println("After sorting:");
        printArray(arr);
    }
}

This program implements the Quick Sort algorithm using the quickSort() and partition() methods. The quickSort() method recursively calls itself to sort the array by dividing it into two smaller sub-arrays and sorting each sub-array separately. The partition() method selects a pivot element from the array and partitions the array into two sub-arrays, one containing elements less than the pivot, and the other containing elements greater than or equal to the pivot.

The printArray() method is a helper method that prints the contents of an array to the console.

The main() method creates an unsorted array of integers and prints the array to the console. It then sorts the array using the quickSort() method and prints the sorted array to the console.