“How to write a code for the quicksort algorithm in Java?”

Here is a Java code implementing the quicksort algorithm.

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

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

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

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

This code implements the quick sort algorithm. In the main function, a target array nums is defined and the quickSort function is called to sort it. The quickSort function uses recursion to perform quick sort, utilizing the partition function to determine the position of the pivot element and divide the array into two subarrays. The partition function selects the rightmost element as the pivot element, then traverses the array, swapping elements less than or equal to the pivot element to the left. Finally, the pivot element is swapped with the last element of the left subarray, and the position of the pivot element is returned. The swap function is used to swap the positions of two elements in the array. Once sorting is complete, the sorted array is outputted.

bannerAds