1.PHP 实现快速排序:
代码语言:javascript复制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 实现快速排序:
代码语言:javascript复制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 实现快速排序:
代码语言:javascript复制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 实现快速排序:
代码语言:javascript复制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)
本文为joshua317原创文章,转载请注明:转载自joshua317博客 https://www.joshua317.com/article/303