Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 1ff5a1b

Browse files
author
Amogh Singhal
authored
Update quick_sort.py
1 parent 57b29ea commit 1ff5a1b

File tree

1 file changed

+26
-34
lines changed

1 file changed

+26
-34
lines changed

‎quick_sort.py‎

Lines changed: 26 additions & 34 deletions
Original file line numberDiff line numberDiff line change
@@ -1,47 +1,39 @@
1-
def swap(a, b):
2-
temp = a
3-
a = b
4-
b = temp
1+
def quick_sort(arr):
2+
quick_sort_helper(arr, 0, len(arr)-1)
53

6-
def quick_sort(array):
7-
quick_sort_helper(array, 0, len(array)-1)
84

95
def quick_sort_helper(arr, first, last):
10-
if first < last:
11-
split_point = partition(arr, first, last)
6+
if first < last:
7+
pi = partition(arr, first, last)
8+
9+
quick_sort_helper(arr, first, pi-1)
10+
quick_sort_helper(arr, pi+1, last)
1211

13-
quick_sort_helper(arr, first, split_point - 1)
14-
quick_sort_helper(arr, split_point + 1, last)
1512

1613
def partition(arr, first, last):
17-
pivot = arr[first]
14+
pivot = arr[first]
15+
16+
left = first+1
17+
right = last
1818

19-
left = first + 1
20-
right = last
19+
done = False
20+
while not done:
21+
while left <= right and arr[left] <= pivot:
22+
left += 1
2123

22-
done = False
24+
while arr[right] >= pivot and right >= left:
25+
right -= 1
2326

24-
while not done:
25-
26-
# move left and right pointers to locate split_point
27-
while left <= right and arr[left] <= pivot:
28-
left += 1
29-
while arr[right] >= pivot and right >= left:
30-
right -= 1
27+
if right < left:
28+
done = True
29+
else:
30+
arr[left], arr[right] = arr[right], arr[left]
3131

32-
# when both pointers cross each other
33-
# we have located the split_point
34-
if right < left:
35-
done = True
36-
else:
37-
# swap the left and right elements
38-
swap(arr[left], arr[right])
32+
arr[first], arr[right] = arr[right], arr[first]
3933

40-
# swap the first and right elements
41-
swap(arr[first], arr[right])
34+
return right
4235

43-
return right
4436

45-
array= [54,26,93,17,77,31,44,55,20]
46-
quick_sort(array)
47-
print(array)
37+
alist= [54,26,93,17,77,31,44,55,20]
38+
quick_sort(alist)
39+
print(alist) # [17, 20, 26, 31, 44, 54, 55, 77, 93]

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /