1def partition(array, begin, end):
2 pivot_idx = begin
3 for i in xrange(begin+1, end+1):
4 if array[i] <= array[begin]:
5 pivot_idx += 1
6 array[i], array[pivot_idx] = array[pivot_idx], array[i]
7 array[pivot_idx], array[begin] = array[begin], array[pivot_idx]
8 return pivot_idx
9
10def quick_sort_recursion(array, begin, end):
11 if begin >= end:
12 return
13 pivot_idx = partition(array, begin, end)
14 quick_sort_recursion(array, begin, pivot_idx-1)
15 quick_sort_recursion(array, pivot_idx+1, end)
16
17def quick_sort(array, begin=0, end=None):
18 if end is None:
19 end = len(array) - 1
20
21 return quick_sort_recursion(array, begin, end)
1def partition(arr, low, high):
2 i = (low-1)
3 pivot = arr[high]
4
5 for j in range(low, high):
6 if arr[j] <= pivot:
7
8 i = i+1
9 arr[i], arr[j] = arr[j], arr[i]
10
11 arr[i+1], arr[high] = arr[high], arr[i+1]
12 return (i+1)
13
14def quickSort(arr, low, high):
15 if len(arr) == 1:
16 return arr
17 if low < high:
18 pi = partition(arr, low, high)
19
20 quickSort(arr, low, pi-1)
21 quickSort(arr, pi+1, high)
22
23arr = [10, 7, 8, 9, 1, 5]
24n = len(arr)
25quickSort(arr, 0, n-1)
26print("Sorted array is:")
27for i in range(n):
28 print("%d" % arr[i]),
1array = [29,99,27,41,66,28,44,78,87,19,31,76,58,88,83,97,12,21,44]
2
3quick_sort(array, 0, len(array) - 1)
4print(array)
5
1def quicksort(arr):
2 if len(arr) <= 1:
3 return arr
4 pivot = arr[len(arr) // 2]
5 left = [x for x in arr if x < pivot]
6 middle = [x for x in arr if x == pivot]
7 right = [x for x in arr if x > pivot]
8 return quicksort(left) + middle + quicksort(right)
9
10print(quicksort([3,6,8,10,1,2,1]))
11# Prints "[1, 1, 2, 3, 6, 8, 10]"
12
1#!/usr/bin/env python3
2# -*- coding: utf-8 -*-
3
4def quickSort(alist):
5 quickSortHelper(alist,0,len(alist)-1)
6
7def quickSortHelper(alist,first,last):
8 if first<last:
9
10 splitpoint = partition(alist,first,last)
11
12 quickSortHelper(alist,first,splitpoint-1)
13 quickSortHelper(alist,splitpoint+1,last)
14
15
16def partition(alist,first,last):
17 pivotvalue = alist[first]
18
19 leftmark = first+1
20 rightmark = last
21
22 done = False
23 while not done:
24
25 while leftmark <= rightmark and alist[leftmark] <= pivotvalue:
26 leftmark = leftmark + 1
27
28 while alist[rightmark] >= pivotvalue and rightmark >= leftmark:
29 rightmark = rightmark -1
30
31 if rightmark < leftmark:
32 done = True
33 else:
34 temp = alist[leftmark]
35 alist[leftmark] = alist[rightmark]
36 alist[rightmark] = temp
37
38 temp = alist[first]
39 alist[first] = alist[rightmark]
40 alist[rightmark] = temp
41
42
43 return rightmark
44
1def quick_sort(array, start, end):
2 if start >= end:
3 return
4
5 p = partition(array, start, end)
6 quick_sort(array, start, p-1)
7 quick_sort(array, p+1, end)
8