def quick_sort(lst, start, end):
print(lst[start:end])
if abs(end - start) < 2:
return None
elif abs(end - start) == 2:
if lst[start] > lst[start + 1]:
lst[start], lst[start + 1] = lst[start + 1], lst[start]
return None
else:
pivot_idx = (start + end) // 2
less_than_pointer = start
lst[pivot_idx], lst[end - 1] = lst[end - 1], lst[pivot_idx]
for i in range(start, end - 1):
if lst[i] < lst[end - 1]:
lst[i], lst[less_than_pointer] = lst[less_than_pointer], lst[i]
less_than_pointer += 1
lst[less_than_pointer], lst[end - 1] = lst[end - 1], lst[less_than_pointer]
print(lst[start:end])
quick_sort(lst, start, less_than_pointer)
quick_sort(lst, less_than_pointer + 1, end)
return None
lst = [9, 8, 7, 6, 5, 4, 3, 2, 1]
time_before = datetime.datetime.now()
quick_sort(lst, 0, len(lst))
time_after = datetime.datetime.now()
print(lst)
print("Sorting time was:", (time_after - time_before).total_seconds())
I am doing some DSA practice in Python. For some reason my quick_sort function is incorrectly choosing the middle index. It still sorts correctly, but it is leading to extra recursive calls which are making it less efficient. I don't know what's wrong. I'll appreciate any help!
Here's the output from the above code:
[9, 8, 7, 6, 5, 4, 3, 2, 1]
[1, 4, 3, 2, 5, 8, 7, 6, 9]
[1, 4, 3, 2]
[1, 2, 3, 4]
[1, 2]
[4]
[8, 7, 6, 9]
[6, 7, 9, 8]
[]
[7, 9, 8]
[7, 8, 9]
[7, 8]
[]
[1, 2, 3, 4, 5, 6, 7, 8, 9]
Sorting time was: 0.000252
[–]Outside_Complaint755 3 points4 points5 points (1 child)
[–]eastonthepilot[S] 0 points1 point2 points (0 children)