python快速排序:
- 方法一:
def quick_sort(L, start, end): if start >= end: return low, high, pivot = start, end, L[start] while low < high: while (low < high) and (L[high] >= pivot): high = high - 1 if low < high: L[low] = L[high] low = low + 1 while (low < high) and (L[low] < pivot): low = low + 1 if low < high: L[high] = L[low] high = high - 1 L[low] = pivot quick_sort(L, start, low - 1) quick_sort(L, low + 1, end) return L
- 方法二:
def quick_sort(L): if len(L) < 2: return L else: left = quick_sort([item for item in L[1:] if item <= L[0]]) right = quick_sort([item for item in L[1:] if item > L[0]]) return left + [L[0]] + right
Java快速排序:
public class Main {
private static void quickSort(int[] L, int start, int end) {
if (start < end) {
int low = start;
int high = end;
int pivot = L[start];
while (low < high) {
while (low < high && L[high] >= pivot) {
high = high - 1;
}
if (low < high) {
L[low] = L[high];
low = low + 1;
}
while (low < high && L[low] < pivot) {
low = low + 1;
}
if (low < high) {
L[high] = L[low];
high = high - 1;
}
L[low] = pivot;
}
quickSort(L, start, low - 1);
quickSort(L, low + 1, end);
}
}
public static void main(String[] args){
int[] L = {33, 2, 46, 84, 5, 2, 44, 60, 15, 60, 74, 27, 26, 28, 89, 8, 51, 90, 15, 14, 75, 97, 83, 6, 29, 44};
quickSort(L, 0, L.length - 1);
for (int i = 0; i < L.length; i++) {
System.out.print(L[i] + " ");
}
}