How to implement the quicksort algorithm in Java?

Quick Sort is a commonly used sorting algorithm that works by dividing the unsorted data into two separate parts during each iteration, with one part having all elements smaller than the other. This process is then repeated recursively on each part until the entire dataset is sorted.

Below is an example code of implementing the quicksort algorithm in Java.

public class QuickSort {
    public static void main(String[] args) {
        int[] arr = {9, 2, 5, 7, 1, 8, 6, 3, 4};
        quickSort(arr, 0, arr.length - 1);
        for (int num : arr) {
            System.out.print(num + " ");
        }
    }

    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);
        }
    }

    public static int partition(int[] arr, int low, int high) {
        // 将第一个元素作为分区点
        int pivot = arr[low];
        while (low < high) {
            // 从右往左找到第一个小于分区点的元素
            while (low < high && arr[high] >= pivot) {
                high--;
            }
            // 将该元素放到左侧
            arr[low] = arr[high];
            // 从左往右找到第一个大于分区点的元素
            while (low < high && arr[low] <= pivot) {
                low++;
            }
            // 将该元素放到右侧
            arr[high] = arr[low];
        }
        // 将分区点放到正确的位置上
        arr[low] = pivot;
        // 返回分区点的索引
        return low;
    }
}

In the above code, the quickSort method implements the recursive calls of the quicksort algorithm, while the partition method is used to partition the array and return the index of the partition point. Each recursive call selects a partition point to divide the array into two subarrays, then performs a quicksort on each subarray. Finally, the partition point is placed in its correct position to complete a pass of sorting. By recursively calling the quicksort algorithm, the entire array can eventually be sorted.

bannerAds