Skip to content

Commit 0ec54fa

Browse files
committed
quicksort: Add quicksort algorithm
rel #2
1 parent a084d52 commit 0ec54fa

File tree

1 file changed

+48
-0
lines changed

1 file changed

+48
-0
lines changed

quicksort/Python/quicksort.py

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
"""
2+
QuickSort Algorithm
3+
- If the list is empty, return the list and terminate. - (Base case)
4+
- Choose a pivot element in the list.
5+
- Take all of the elements that are less than or equal to the pivot and use
6+
quicksort on them.
7+
- Take all of the elements that are greater than the pivot and use quicksort
8+
on them.
9+
- Return the concatenation of the quicksorted list of elements that are less
10+
than or equal to the pivot, the pivot, and the quicksorted list of elements
11+
that are greater than the pivot.
12+
"""
13+
14+
15+
def quicksort(arr):
16+
"""
17+
Fuction to do quicksort.
18+
19+
:param arr: A list of element to sort.
20+
"""
21+
less = []
22+
pivotList = []
23+
more = []
24+
25+
if len(arr) <= 1:
26+
return arr
27+
else:
28+
pivot = arr[0]
29+
for i in arr:
30+
if i < pivot:
31+
less.append(i)
32+
elif i > pivot:
33+
more.append(i)
34+
else:
35+
pivotList.append(i)
36+
less = quicksort(less)
37+
more = quicksort(more)
38+
return less + pivotList + more
39+
40+
41+
def main():
42+
arr = [6, 5, 4, 3, 2, 1]
43+
print('Sorted element using Quicksort: {}'.format(
44+
' '.join(map(str, quicksort(arr)))))
45+
46+
47+
if __name__ == '__main__':
48+
main()

0 commit comments

Comments
 (0)