What is the method for implementing quicksort in Java?

Quick Sort is a commonly used sorting algorithm that works by selecting a pivot value, dividing the array into two parts, with elements on the left side smaller than the pivot value and elements on the right side larger than the pivot value, and then recursively sorting the left and right parts individually. Here is a method to implement Quick Sort in Java.

public class QuickSort {
    public static void quickSort(int[] arr, int low, int high) {
        if (arr == null || arr.length == 0) {
            return;
        }
        if (low >= high) {
            return;
        }

        // Choose the pivot element
        int middle = low + (high - low) / 2;
        int pivot = arr[middle];

        // Make left < pivot and right > pivot
        int i = low, j = high;
        while (i <= j) {
            while (arr[i] < pivot) {
                i++;
            }
            while (arr[j] > pivot) {
                j--;
            }
            if (i <= j) {
                int temp = arr[i];
                arr[i] = arr[j];
                arr[j] = temp;
                i++;
                j--;
            }
        }

        // Recursively sort two sub-parts
        if (low < j) {
            quickSort(arr, low, j);
        }
        if (high > i) {
            quickSort(arr, i, high);
        }
    }

    public static void main(String[] args) {
        int[] arr = {6, 3, 8, 2, 9, 1};
        quickSort(arr, 0, arr.length - 1);
        System.out.println("Sorted array: " + Arrays.toString(arr));
    }
}

In the given code, the quickSort method is used to implement quick sort, with low representing the start position of the array and high representing the end position. In the main method, we define an array arr, then call the quickSort method to sort the array, and finally output the sorted array.

Leave a Reply 0

Your email address will not be published. Required fields are marked *


广告
Closing in 10 seconds
bannerAds