CARVIEW |
Select Language
HTTP/2 200
cache-control: public, max-age=300, stale-while-revalidate=604800
referrer-policy: strict-origin-when-cross-origin
x-app-version: v251008-h-251010-1202
x-content-type-options: nosniff
x-frame-options: SAMEORIGIN
x-xss-protection: 1; mode=block
x-app-type: Learn
x-middleware-rewrite: /answers/howdev/how-to-implement-quicksort-in-python
x-nextjs-cache: MISS
etag: W/"13y4hl6smfws2lg"
content-type: text/html; charset=utf-8
x-cloud-trace-context: 8f3f81aed56b91af94cb7f7dc3484137
date: Sun, 12 Oct 2025 06:44:49 GMT
server: Google Frontend
via: 1.1 google
vary: Accept-Encoding
content-encoding: gzip
x-cache-status: miss
alt-svc: h3=":443"; ma=2592000,h3-29=":443"; ma=2592000
How to implement QuickSort in Python 



How to implement QuickSort in Python
QuickSort is an in-place sorting algorithm with worst-case time complexity of n2.
Implementation
QuickSort can be implemented both iteratively and recursively. We’ll mainly focus on the recursive implementation, as it is far more convenient, intuitive, and simplistic – iterative implementation is generally unrecommended. Arrays are used as an example here, but QuickSort can be implemented on other data structures (like linked lists) as well.
The algorithm can be broken down into three parts:
- Partitioning the array about the pivot.
- Passing the smaller arrays to the recursive calls.
- Joining the sorted arrays that are returned from the recursive call and the pivot.
1 of 16
1 of 16
1 of 16
1 of 16
1 of 16
In the above illustration, we used the first element of the array as a pivot, even though any of the elements could be taken.
Code
def QuickSort(arr):elements = len(arr)#Base caseif elements < 2:return arrcurrent_position = 0 #Position of the partitioning elementfor i in range(1, elements): #Partitioning loopif arr[i] <= arr[0]:current_position += 1temp = arr[i]arr[i] = arr[current_position]arr[current_position] = temptemp = arr[0]arr[0] = arr[current_position]arr[current_position] = temp #Brings pivot to it's appropriate positionleft = QuickSort(arr[0:current_position]) #Sorts the elements to the left of pivotright = QuickSort(arr[current_position+1:elements]) #sorts the elements to the right of pivotarr = left + [arr[current_position]] + right #Merging everything togetherreturn arrarray_to_be_sorted = [4,2,7,3,1,6]print("Original Array: ",array_to_be_sorted)print("Sorted Array: ",QuickSort(array_to_be_sorted))
Relevant Answers
Explore Courses
Free Resources
Copyright ©2025 Educative, Inc. All rights reserved