Python Why is this quicksort not sorting properly? -


i have been trying implement quicksort function using python last 3 weeks point , sorts mostly, there few items out of place.

i don't think understand quicksort properly, if can see why code please explain.

i have chosen pivot first object in list, "low", , comparing rest of list. if object @ list index "low" greater list index "i" (in loop), switch "i" "e" (initially indexed item "low + 1"), if switch, "e" increments. if doesn't switch, "i" increments (because of loop).

once loop finished, decrement "e" (to index highest number in list lower pivot) switch "low" (index of pivot)

i quicksort left , right halves of list using "e" determine list splits. - seems point code fails sort.

i believe how quicksort works, haven't been able make work. if know i'm missing or if it's 1 of lines, please let me know. problem appreciated.

(ps. "main" function passing list of 20 length variables of 0-19 value quicksort , python build-in sort)

import random   def quick(a, low, high):     if high <= low:         return     elif high > low:         e = low+1         in range(e, high):             if a[low] > a[i]:                 a[i], a[e] = a[e], a[i]                 e +=1         e -= 1         a[low], a[e] = a[e], a[low]         quick(a, low, e-1)         quick(a, e+1, high)   def main():     lista = []     listb = []     in range(20):         int = random.randrange(0, 19)         lista.append(int)     in range(len(lista)):         listb.append(lista[i])     print("list (before sort)" + str(lista))     print("list b (before sort)" + str(listb))     quick(lista, 0, len(lista)-1)     print("\nlist (after sort)" + str(lista))     print("list b (before sort)" + str(listb))     listb.sort()     print("\nlist (after sort)" + str(lista))     print("list b (after sort)" + str(listb))   main() 

your problem you're ignoring 1 number each split. range(min, max) gives list includes min not max, ending rather on max-1

quick(lista, 0, len(lista)-1)

should

quick(lista, 0, len(lista)),

and

quick(a, low, e-1)

should

quick(a, low, e).


Comments

Popular posts from this blog

sublimetext3 - what keyboard shortcut is to comment/uncomment for this script tag in sublime -

java - No use of nillable="0" in SOAP Webservice -

ubuntu - Laravel 5.2 quickstart guide gives Not Found Error -