以下是Java中的快速排序的实现:

public class QuickSort {
    
    public void sort(int[] arr) {
        quickSort(arr, 0, arr.length - 1);
    }
    
    private void quickSort(int[] arr, int left, int right) {
        if (left < right) {
            int pivotIndex = partition(arr, left, right);
            quickSort(arr, left, pivotIndex - 1);
            quickSort(arr, pivotIndex + 1, right);
        }
    }
    
    private int partition(int[] arr, int left, int right) {
        int pivot = arr[right];
        int i = left - 1;
        for (int j = left; j < right; j++) {
            if (arr[j] < pivot) {
                i++;
                swap(arr, i, j);
            }
        }
        swap(arr, i + 1, right);
        return i + 1;
    }
    
    private void swap(int[] arr, int i, int j) {
        int temp = arr[i];
        arr[i] = arr[j];
        arr[j] = temp;
    }
}

在这个实现中,我们采用了经典的快速排序算法,即将一个元素作为枢轴(pivot),将比它小的元素放在它的左侧,比它大的元素放在它的右侧,然后递归地对左右两个子数组进行排序。在实现过程中,我们使用了双指针法来进行元素的交换和移动。

使用示例:

int[] arr = {5, 2, 9, 1, 5, 6};
QuickSort sorter = new QuickSort();
sorter.sort(arr);
System.out.println(Arrays.toString(arr));  // [1, 2, 5, 5, 6, 9]
使用java快速排序

原文地址: https://www.cveoy.top/t/topic/bI6V 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录