Skip to content

Instantly share code, notes, and snippets.

@nishidy
Last active April 8, 2022 01:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nishidy/48bd45582e255140c6bb5542f830c83f to your computer and use it in GitHub Desktop.
Save nishidy/48bd45582e255140c6bb5542f830c83f to your computer and use it in GitHub Desktop.
Quick Sort in Python
class Sorter:
def __init__(self,data):
self.orig = data.copy()
self.data = data
def do_qsort(self):
print("Original data",self.orig)
self.run_qsort(0,len(self.data)-1)
print("Sorted data ",self.data)
def run_qsort(self,i,j):
self.swap(i,int((i+j)/2))
k=i+1
for m in range(i+1,j+1):
if self.data[m]<self.data[i]:
self.swap(m,k)
k+=1
self.swap(i,k-1)
if i+1<k:
self.run_qsort(i,k-1)
if k<j:
self.run_qsort(k,j)
def swap(self,i,j):
self.data[i], self.data[j] = self.data[j], self.data[i]
Sorter([5,3,1,0,2,4,9,7,6,8]).do_qsort()
Sorter([9,8,7,6,5,4,3,2,1,0]).do_qsort()
Sorter([2,2,2,2,1,1,1,1,0,0]).do_qsort()
@nishidy
Copy link
Author

nishidy commented May 2, 2017

$ python quick_sort.py
Original data [5, 3, 1, 0, 2, 4, 9, 7, 6, 8]
Sorted data   [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Original data [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
Sorted data   [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Original data [2, 2, 2, 2, 1, 1, 1, 1, 0, 0]
Sorted data   [0, 0, 1, 1, 1, 1, 2, 2, 2, 2]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment