Mark As Completed Discussion

Quicksort

Quicksort is a widely-used sorting algorithm that employs a divide-and-conquer strategy. It works by selecting a pivot element from the array and partitioning the other elements into two sub-arrays, according to whether they are less than or greater than the pivot. The sub-arrays are then sorted recursively.

Here's an implementation of the quicksort algorithm in Java:

TEXT/X-JAVA
1public class QuickSort {
2
3    public static void quickSort(int[] arr, int low, int high) {
4        if (low < high) {
5            int pivot = partition(arr, low, high);
6            quickSort(arr, low, pivot - 1);
7            quickSort(arr, pivot + 1, high);
8        }
9    }
10
11    public static int partition(int[] arr, int low, int high) {
12        int pivot = arr[high];
13        int i = low - 1;
14
15        for (int j=low; j < high; j++) {
16            if (arr[j] <= pivot) {
17                i++;
18                int temp = arr[i];
19                arr[i] = arr[j];
20                arr[j] = temp;
21            }
22        }
23
24        int temp = arr[i + 1];
25        arr[i + 1] = arr[high];
26        arr[high] = temp;
27
28        return i + 1;
29    }
30
31    public static void main(String[] args) {
32        int[] arr = {5, 2, 7, 1, 3, 6, 4};
33        quickSort(arr, 0, arr.length - 1);
34        for (int num : arr) {
35            System.out.print(num + " ");
36        }
37    }
38
39}
JAVA
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment