From 5509981c5c3b17055bba940cbbea9de86e0f1187 Mon Sep 17 00:00:00 2001 From: vincenzobaz Date: Thu, 28 Jul 2016 23:48:23 +0200 Subject: [PATCH] add quicksort --- QuickSort.py | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 QuickSort.py diff --git a/QuickSort.py b/QuickSort.py new file mode 100644 index 000000000..79362de46 --- /dev/null +++ b/QuickSort.py @@ -0,0 +1,29 @@ + +def quicksort(A, p, r): + if p < r: + q = partition(A, p, r) + quicksort(A, p, q - 1) + quicksort(A, q + 1, r) + + +def partition(A, p, r): + x = A[r] + i = p - 1 + for j in range(p, r): + if A[j] <= x: + i += 1 + tmp = A[i] + A[i] = A[j] + A[j] = tmp + tmp = A[i+1] + A[i+1] = A[r] + A[r] = tmp + return i + 1 + + +if __name__ == "__main__": + A = [8, 4, 5, 7, 1, 2, 3, 6] + # partition(A, 0, 7) + print(A) + quicksort(A, 0, 7) + print(A)