Skip to content

Commit c3c517d

Browse files
committed
add quick sort in python
1 parent e72cd53 commit c3c517d

1 file changed

Lines changed: 25 additions & 0 deletions

File tree

QuickSort/Python/QuickSort.py

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
def quicksort(array, startIndex, endIndex):
2+
if startIndex < endIndex:
3+
middle = partition(array, startIndex, endIndex)
4+
quicksort(array, startIndex, middle - 1)
5+
quicksort(array, middle + 1, endIndex)
6+
return array
7+
8+
def partition(array, startIndex, endIndex):
9+
pivot = startIndex + (endIndex - startIndex) // 2;
10+
pivotIndex = startIndex
11+
array[pivot], array[endIndex] = array[endIndex], array[pivot]
12+
13+
for i in range(startIndex, endIndex):
14+
if array[i] < array[endIndex]:
15+
array[pivotIndex], array[i] = array[i], array[pivotIndex]
16+
pivotIndex += 1
17+
18+
array[endIndex], array[pivotIndex] = array[pivotIndex], array[endIndex]
19+
return pivotIndex
20+
21+
if __name__ == '__main__':
22+
arr = [97, 200, 100, 101, 211, 107]
23+
print("My array is:\n", [x for x in arr])
24+
print("\nMy sorted array is: ")
25+
print(quicksort(arr, 0, len(arr) - 1))

0 commit comments

Comments
 (0)