785. 快速排序

90 阅读1分钟

785. 快速排序 - AcWing题库

Question

Content

给定你一个长度为 n 的整数数列。

请你使用快速排序对这个数列按照从小到大进行排序。

并将排好序的数列按顺序输出。

输入格式

输入共两行,第一行包含整数 n 。

第二行包含 n 个整数(所有整数均在 1 ∼ 10910^9 范围内),表示整个数列。

输出格式

输出共一行,包含 n 个整数,表示排好序的数列。

数据范围

1 ≤ n ≤ 100000

输入样例:

5
3 1 2 4 5

输出样例:

1 2 3 4 5

Solution

Java

import java.util.Scanner;
import java.util.stream.IntStream;

public class QuickSort {

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        // Read the number of elements (n) from the user
        int n = scanner.nextInt();

        // Initialize an array 'nums' and populate it with user-input values
        int[] nums = IntStream.range(0, n)
                .map(i -> scanner.nextInt())
                .toArray();

        // Call the quickSort method to sort the 'nums' array
        quickSort(nums, 0, n - 1);

        // Print the sorted array elements to the console
        IntStream.range(0, n).mapToObj(i -> nums[i] + " ")
                .forEach(System.out::print);

        // Close the scanner to release resources
        scanner.close();
    }

    // QuickSort algorithm implementation
    private static void quickSort(int[] nums, int left, int right) {
        if (left >= right) {
            return; // Base case: If the subarray is empty or has one element, it is already sorted.
        }

        // Initialize two pointers 'i' and 'j' and choose a pivot element 'p'
        int i = left - 1, j = right + 1, p = nums[left + right >> 1];

        // Partition the array into two subarrays
        while (i < j) {
            // Find elements smaller than the pivot from the left
            while (nums[++i] < p) ;
            // Find elements larger than the pivot from the right
            while (nums[--j] > p) ;
            if (i < j) {
                // Swap elements if 'i' is smaller than 'j'
                swap(nums, i, j);
            }
        }

        // Recursively sort the subarrays on the left and right of the pivot
        quickSort(nums, left, j);
        quickSort(nums, j + 1, right);
    }

    // Helper function to swap two elements in the array
    private static void swap(int[] nums, int left, int right) {
        // Bitwise XOR-based swap operation to exchange two values without using a temporary variable
        nums[left] = nums[left] ^ nums[right];
        nums[right] = nums[left] ^ nums[right];
        nums[left] = nums[left] ^ nums[right];
    }
}