溫馨提示×

Java快速排序的方法有哪些

小億
84
2024-05-27 15:10:15
欄目: 編程語言

Java中常用的快速排序方法有以下幾種:

  1. 使用遞歸實現(xiàn)的快速排序方法:
public void quickSort(int[] arr, int low, int high) {
    if (low < high) {
        int pivot = partition(arr, low, high);
        quickSort(arr, low, pivot - 1);
        quickSort(arr, pivot + 1, high);
    }
}

public int partition(int[] arr, int low, int high) {
    int pivot = arr[high];
    int i = low - 1;
    for (int j = low; j < high; j++) {
        if (arr[j] < pivot) {
            i++;
            int temp = arr[i];
            arr[i] = arr[j];
            arr[j] = temp;
        }
    }
    int temp = arr[i + 1];
    arr[i + 1] = arr[high];
    arr[high] = temp;
    return i + 1;
}
  1. 使用棧實現(xiàn)的非遞歸快速排序方法:
public void quickSort(int[] arr, int low, int high) {
    Stack<Integer> stack = new Stack<>();
    stack.push(low);
    stack.push(high);

    while (!stack.isEmpty()) {
        high = stack.pop();
        low = stack.pop();
        int pivot = partition(arr, low, high);

        if (pivot - 1 > low) {
            stack.push(low);
            stack.push(pivot - 1);
        }
        if (pivot + 1 < high) {
            stack.push(pivot + 1);
            stack.push(high);
        }
    }
}

public int partition(int[] arr, int low, int high) {
    int pivot = arr[high];
    int i = low - 1;
    for (int j = low; j < high; j++) {
        if (arr[j] < pivot) {
            i++;
            int temp = arr[i];
            arr[i] = arr[j];
            arr[j] = temp;
        }
    }
    int temp = arr[i + 1];
    arr[i + 1] = arr[high];
    arr[high] = temp;
    return i + 1;
}

這些方法都是基于快速排序的原理實現(xiàn)的,可以根據(jù)需要選擇合適的方法來實現(xiàn)快速排序算法。

0