Yet another post for the crawlers to better index my site for algorithms and as a repository for Python code. The quick sort algorithm is well explained in the topmost Google search result for ‘Quick Sort Python Code’, but the code is unnecessarily convoluted. Instead, go with the code below.
In it, I assume the pivot to be the first element. You can easily add a function to randomize selection of the pivot. Choosing a random pivot minimizes the chance that you will encounter worst-case O(n2) performance. Always choosing first or last would cause worst-case performance for nearly-sorted or nearly-reverse-sorted data.
|if len(x) == 1 or len(x) == 0:|
|pivot = x|
|i = 0|
|for j in range(len(x)-1):|
|if x[j+1] < pivot:|
|x[j+1],x[i+1] = x[i+1], x[j+1]|
|i += 1|
|x,x[i] = x[i],x|
|first_part = quicksort(x[:i])|
|second_part = quicksort(x[i+1:])|
|return first_part + second_part|
|alist = [54,26,93,17,77,31,44,55,20]|