用php/java/go/python 分别实现快速排序

1.PHP 实现快速排序:

function quick_sort($array) {
    if (count($array) <= 1) {
        return $array;
    }
    $pivot = $array[0];
    $left = $right = array();
    for ($i = 1; $i < count($array); $i++) {
        if ($array[$i] < $pivot) {
            $left[] = $array[$i];
        } else {
            $right[] = $array[$i];
        }
    }
    return array_merge(quick_sort($left), array($pivot), quick_sort($right));
}

2.Java 实现快速排序:

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

public static int partition(int[] array, int left, int right) {
    int pivotValue = array[right];
    int pivotIndex = left;
    for (int i = left; i < right; i++) {
        if (array[i] < pivotValue) {
            int temp = array[i];
            array[i] = array[pivotIndex];
            array[pivotIndex] = temp;
            pivotIndex++;
        }
    }
    int temp = array[pivotIndex];
    array[pivotIndex] = array[right];
    array[right] = temp;
    return pivotIndex;
}

3.Go 实现快速排序:

func quickSort(array []int, left, right int) {
    if left < right {
        pivotIndex := partition(array, left, right)
        quickSort(array, left, pivotIndex-1)
        quickSort(array, pivotIndex+1, right)
    }
}

func partition(array []int, left, right int) int {
    pivotValue := array[right]
    pivotIndex := left
    for i := left; i < right; i++ {
        if array[i] < pivotValue {
            array[i], array[pivotIndex] = array[pivotIndex], array[i]
            pivotIndex++
        }
    }
    array[pivotIndex], array[right] = array[right], array[pivotIndex]
    return pivotIndex
}

Python 实现快速排序:

def quick_sort(array):
    if len(array) <= 1:
        return array
    pivot = array[0]
    left, right = [], []
    for i in range(1, len(array)):
        if array[i] < pivot:
            left.append(array[i])
        else:
            right.append(array[i])
    return quick_sort(left) + [pivot] + quick_sort(right)

 

posted @ 2024-03-08 15:08  joshua317  阅读(4)  评论(0编辑  收藏  举报