Тёмный
No video :(

Python: QuickSort algorithm explained 

Oggi AI - Artificial Intelligence Today
Подписаться 77 тыс.
Просмотров 113 тыс.
50% 1

Example of how to implement a Quick Sort algorithm in Python 3, with code. Quick Sort is a recursive, divide-and-conquer sorting algorithm.
PYTHON SORTING ALGORITHMS
► Insertion Sort • Python: Insertion Sort...
► Selection Sort • Python: SelectionSort ...
► Bubble Sort • Python: BubbleSort sor...
► Merge Sort • Python: MergeSort algo...
► Quick Sort • Python: QuickSort algo...
► Radix Sort • RADIX Sort in Python |...
Code: bit.ly/python_s...
Twitter: / joejamesusa
Subscribe: bit.ly/like-th...
#Python

Опубликовано:

 

8 июн 2015

Поделиться:

Ссылка:

Скачать:

Готовим ссылку...

Добавить в:

Мой плейлист
Посмотреть позже
Комментарии : 105   
@evanzhao3887
@evanzhao3887 4 года назад
Great explanation! I love the way you used "border" to name your pointer, instead of plain "i" and "j". It makes the algorithm much easier to understand! Thank you!
@oggiai
@oggiai 9 лет назад
See code on my GitHub repository here, github.com/joeyajames/Python
@jeethuutube
@jeethuutube 8 лет назад
Could not find quicksort in python
@jeethuutube
@jeethuutube 8 лет назад
ok, I got it. thanks.. really love the github python codes.
@joyoptimal6286
@joyoptimal6286 6 лет назад
From the github file sortingAlgorithms, I get an error in line 112 for threshold not defined.
@changerfeng6147
@changerfeng6147 5 лет назад
he said set to 20 in video
@user-ed1zt3ke3r
@user-ed1zt3ke3r 5 лет назад
Hi Joe, give a look to this code for getPivot, guess it works better. def get_pivot(A, low, hi): mid = (low+hi)//2 pivot = hi if A[mid]>A[low] and A[mid]A[hi] and A[low]
@Philippe.C.A-R
@Philippe.C.A-R 5 лет назад
on the video: 41 is never actually compared to the pivot. Had it been any other value lower than the pivot in place of 41 then it would have ended in the right end side side partition.I suggest that one step was skipped by not comparing " border" to the pivot. Additionally at the end of each run pict should be swapped with border -1. I ran a few examples this way, and it seems to work fine now. Lmk all if if you reached the same conclusions or I missed something.
@manishbolbanda9872
@manishbolbanda9872 3 года назад
at 7:25 line 28, you increment border before swapping, just wanna make sure its correct ?
@johnnyphoney5669
@johnnyphoney5669 8 лет назад
Isn't it too complicated? I wrote it for few minutes and it's just 4 lines and by my opinion a lot easier to understand: ``` def quick_sort(a_list): if len(a_list) < 2: return a_list lesser = quick_sort([x for x in a_list[1:] if x a_list[0]]) return sum([lesser, [a_list[0]], bigger], []) ```
@oggiai
@oggiai 8 лет назад
very nice!
@zine2hamster
@zine2hamster 8 лет назад
cool! what is the sum() for? and should I expect the efficiency of this code to be similar?
@johnnyphoney5669
@johnnyphoney5669 8 лет назад
sum() is needed to concatenate few lists to single one. I don't know what to say about efficiency, some benchmarks needs to be written with different use-cases.
@rickventer7380
@rickventer7380 8 лет назад
You're a Fucking genius
@guksungan1267
@guksungan1267 7 лет назад
This is definitely clearer but generates a list every function call, thus not sorting in place like the video. I would prefer mergesort at this point, but thank you for your contribution!
@balakrishnavaidyanathan8572
@balakrishnavaidyanathan8572 4 года назад
Dear Joe James your python videos are great.keep sending some more
@dilio8457
@dilio8457 8 лет назад
This is the best and most visually explained concept of quicksort.
@oggiai
@oggiai 8 лет назад
Thanks!
@abovebelow4061
@abovebelow4061 2 года назад
what is threshold supposed to be in quicksort2?
@Fire_Fly_101
@Fire_Fly_101 4 года назад
Is there a flaw with this algorith when I sort the following list? [32,18,9,27,28,21,29,7,12,4] first partition gives [4,9,27,21,7,12,28,32,18,29 and 28 was the pivot..But still got 18 on the right
@ehtashambaig912
@ehtashambaig912 4 года назад
I tried it and see no flaw in it and I get the correct sorted list as the output.
@neeks3367
@neeks3367 7 лет назад
Is there any reason why you couldn't do a while loop in the partition method for the sort? while i pivot array[i], array[j] = array[j], array[i] i++
@oggiai
@oggiai 7 лет назад
Try it and let me know if it works.
@karima_ax
@karima_ax 4 года назад
How would you write quick sort algorithm in pseudocode?
@slater267
@slater267 7 лет назад
Thanks for the video Joe. While the code you provide may correctly sort, I'm having a problem with visual demonstration provided. 1. the #41 is never compared to the pivot in the first pass. but every number would need to be checked to insure all #'s less than pivot are to left of pivot. For example change 41 to 1 an the visual example will not work because no comparison is made with that position. 2. at (2:55) if 13 happened to be 21, the swap would not happen, and so you would not be able to swap the pivot with that boarder location, or if you did there would be a 21 in the first location
@oggiai
@oggiai 7 лет назад
+slater267 are you referring to the code in the video or the latest code on my GitHub site?
@Mr_Yod
@Mr_Yod 3 года назад
1.Actually 41 is compared to the pivot. If you have PyCharm try the algorithm with the debug function. 2. If 13 happened to be a 21 then THAT would have been chosen as pivot. =)
@SO-jp6gh
@SO-jp6gh 2 года назад
Seems like we never compared the element in the initial border position with the pivot? For example, in the first pass, the initial border element 41 never got compared to the first pivot? We just got lucky that it happens to belong in the right half so the fact that it never got compared ended up not hurting us?
@SO-jp6gh
@SO-jp6gh 2 года назад
When we do quicksort of the right half, seems like 29 never got compared to the pivot, so we got lucky that it's lower and got swapped into the first position?
@NvideaMan808
@NvideaMan808 7 лет назад
At 2:54 , if the 8th term was something like 80 and not 13, you wouldn't switch it with the border. Thus you finished going through the list. But what would you do with the pivot and border? As at that specific instance, the border is 54 so you wouldn't switch it with 17 as then you would have 54 on the left side. IE: 17, 5, 6, 3 ,54, 41, 29, 22, 80 where 17 is the pivot, 54 is the border, and you've reached the final value of 80 that you compare with your pivot
@gabkov
@gabkov 5 лет назад
u have to swap with border-1
@saurabhmahra4084
@saurabhmahra4084 4 года назад
it was so easy to understand explaination. thank you very much.
@jmcremer
@jmcremer 8 лет назад
get_pivot (starting near 6:29) is incorrect, or at least does not always return the index of the median of the three values considered. Consider A[low] == 10, A[mid] == 5, A[hi] == 0. get_pivot will return hi in this case but should return mid.
@oggiai
@oggiai 8 лет назад
+Jim Cremer you're right, thanks! I rewrote the get_pivot function and just pushed it to github. This code works, and it actually improves performance. def get_pivot(A, low, hi): mid = (hi + low) // 2 s = sorted([A[low], A[mid], A[hi]]) if s[1] == A[low]: return low elif s[1] == A[mid]: return mid return hi
@Mr_Yod
@Mr_Yod 3 года назад
@@oggiai You could call the quicksort function on s. :o =)
@manishbolbanda9872
@manishbolbanda9872 3 года назад
thanks for this playlist all your videos in this playlist ar awesome.
@thndesmondsaid
@thndesmondsaid 4 года назад
in the partition method, why do we increase the value of border before performing the swap?
@HarshvardhanKanthode
@HarshvardhanKanthode 3 года назад
I have the exact same doubt, did you get it?
@danielqiu4018
@danielqiu4018 7 лет назад
I may be wrong, but in the partition function, within the for loop, shouldn't you increment your border position after swapping the border element with the current element? 7:00
@danielqiu4018
@danielqiu4018 7 лет назад
Never mind. It's because you keep the pivot at the low until you switch it at the end of the for loop.
@oggiai
@oggiai 7 лет назад
+Daniel Qiu hmm, best way to find out is to download the latest code from my GitHub site and test it. Www.github.com/joeyajames/Python
@oggiai
@oggiai 7 лет назад
+Daniel Qiu best way to find out is download the code from my GitHub site and test it, GitHub.com/joeyajames/Python
@michalvolf4973
@michalvolf4973 3 года назад
Time 0:45 13 is smaller than pivot and is on the right side
@nisargsheth9841
@nisargsheth9841 4 года назад
random pivots does not ensure nlogn...worst case time complexity is still O(n^2) e.g. when all the elements are identical. the only way of ensuring nlogn is by choosing a pivot close to the median
@jameskerr9155
@jameskerr9155 3 года назад
great video, ty for keeping the video short
@donkeykong5616
@donkeykong5616 3 года назад
Good stuff mate
@sirseatofbelt
@sirseatofbelt 7 лет назад
Hey this is great! I have to write basically this for a class assignment and then do a bunch of stuff with it. So this is really handy for getting me started!
@bogdankapusta6336
@bogdankapusta6336 7 лет назад
Hello, Joe. thank you for great videos. Can you tell me please why in your python file you measure execution time with "t1 = time.clock()", but not with cProfile library? Thank you
@ukakkad2010
@ukakkad2010 5 лет назад
Mr. James one minor doubt, how exactly do we decide on the border element??? is it the element immediately after the pivot ??
@rahulraj233
@rahulraj233 6 лет назад
@06:05 Change to quick_sort2(A, low, p) to get the correct final answer.
@nahumcollicott9355
@nahumcollicott9355 4 года назад
This might be a "duh" question like my lat, but I tried to implement the code you have in this video, but don;t understand what to use in place of "hi" and "low." Mid is defined in getPivot but many functions use low and hi as parameters. I try using their places within the list [0] and [-1] and tha does not work either. I feel like I am missing something, as defining them yields syntax errors.
@oggiai
@oggiai 4 года назад
Just download my code and run it as-is. It will work. Hi and low are variables that are used inside the function. They take on whatever values you pass in your function call.
@nahumcollicott9355
@nahumcollicott9355 4 года назад
@@oggiai i tried that and still get errors with low and hi not being defined. When I call quickSort, do I need to call and give parameters to every function within it?
@krishind99
@krishind99 3 года назад
Thanks for the video, but there were a lot of comparisons that were not right, be it on the first iteration, left iteration and median for right iteration. We’re they deliberate to see if we comment???? Lol. Keep up the good work
@tanphan3970
@tanphan3970 5 лет назад
hello Joe James, what is threshold in quick_sort2 function?
@mrmcchewy6328
@mrmcchewy6328 4 года назад
I know you posted this 7 months ago and don't care anymore but the threshold is just a certain length of the list that if it is less than that you will use a different sorting algorithm to make quick sort more efficient because quick sort is bad on small lists.
@nehalkamal8169
@nehalkamal8169 4 года назад
@@mrmcchewy6328 where i can define the threshold or set it ??
@mrmcchewy6328
@mrmcchewy6328 4 года назад
@@nehalkamal8169 whatever your threshold number is probably 7 or 6 for this sorting algorithm you just do if (length < 7) and then call the other sorting method
@nehalkamal8169
@nehalkamal8169 4 года назад
@@mrmcchewy6328 Thank you
@mrmcchewy6328
@mrmcchewy6328 4 года назад
@@nehalkamal8169 No problem. Are you doing a school assignment or just practicing sorting algorithms in python?
@BeingCreativeAI
@BeingCreativeAI 8 лет назад
Good Video James
@divx07722
@divx07722 4 года назад
What if low>hi? Pls explain
@saitaro
@saitaro 5 лет назад
threshold in quick_sort2 is not defined.
@serhiypidkuyko4206
@serhiypidkuyko4206 6 лет назад
Hi. Your (wrong) explanation doesn't match with your (right) code. 1. border = left (not left+1) 2. every time an item less then pivot found - only then! border+=1 - and only now! the found item is swapped with the border one only in this case all the less-than-pivot items jumped to the left of the border with last of them exactly on the border Thank you for your very short and clear and logical code of the quick sort
@serhiypidkuyko4206
@serhiypidkuyko4206 6 лет назад
Since: 1.pivotIndex=low -> it would be better to write: "for i in range(low+1, hi+1)" 2.in get_pivot we already compared three values A[low], A[mid], A[hi] . So it would be reasonable to send: pivotIndex -> low+1, lesser -> low, larger ->r. And start with border=low+1 and "... range(low+2,hi+1)"
@nipunhi
@nipunhi 5 лет назад
@@serhiypidkuyko4206 This has me confused as well. But I don't think it'll matter because A[low] < pivotValue will always return false, and when it returns true, the border is incremented to the right. It is slightly different from the example explanation though.
@diwu4005
@diwu4005 5 лет назад
I think the algorithm you explained is wrong. Consider array 5 6 7 8 9 10. 5 is the pivot and 6 is the boarder, since 7 8 9 10 is all greater than 5, we don't swap and thing but pivot and board. This gives 6 5 7 8 9 10 which 6 appears to the left of 5.
@chanwoolee303
@chanwoolee303 5 лет назад
Pivot is not 5, but 7. Look at get_pivot function.
@diwu4005
@diwu4005 5 лет назад
@@chanwoolee303 The problem is not the pivot. It's the boarder he explained in the video. He mentioned specifically to use the first element as the pivot instead of a random one. The boarder should start as the same index as the pivot and only increase by one whenever you find a smaller key, not to put the boarder directly at index of pivot + 1.
@noone9293
@noone9293 4 года назад
Y we choose 22 has pivot
@LapisGarter
@LapisGarter 8 лет назад
Thank you.
@colorfullss3458
@colorfullss3458 4 года назад
Hello dear sir , I need help in parallel quicksort with python, please help me
@oggiai
@oggiai 4 года назад
Parallel Quicksort?
@colorfullss3458
@colorfullss3458 4 года назад
@@oggiai yes parallel quicksort
@colorfullss3458
@colorfullss3458 4 года назад
I sutdent it is my final project if you help with it , I can pay few mounth, please i really need
@qalishahauditore7980
@qalishahauditore7980 6 лет назад
You're the best!
@mohithsankar4725
@mohithsankar4725 4 года назад
why use a algorithm when list is already sorted?
@oggiai
@oggiai 4 года назад
People call sort on already sorted lists very often. Usually they don’t know it’s sorted.
@Mr_Yod
@Mr_Yod 3 года назад
@@oggiai You could just add a call to a is_sorted(lista) function inside the sorting function.
@tushargoyaliit
@tushargoyaliit 5 лет назад
Awesome
@legendofakuma8827
@legendofakuma8827 4 года назад
i like the music
@mumenyanyamu2524
@mumenyanyamu2524 5 лет назад
I love this. it is very helpful, putting this algorithms into practice. Problem is, when i try accessing the link above, it results in a 404
@oggiai
@oggiai 5 лет назад
Www.github.com/joeyajames
@ঋতুপর্ণা
@ঋতুপর্ণা 9 месяцев назад
Saviour
@Nadikii
@Nadikii 7 лет назад
I can't believe I just wasted 30min of my life trying to figure out this code just to realice that the get_piv function is broken! This might not be a big deal for many, but for beginner programmers it can be very frustrating. This video has a great description on how the algorithm works, but this guy should try testing his code a few more times before making a video with a broken code.
@oggiai
@oggiai 7 лет назад
+Nadia Wangberg did you retype the code on your own, or download the latest code from my GitHub site? Also, what version of Python are you using? I think I wrote this in v3.3, so it may require changes to work in v2.7. Please provide details of the problem that could help others.
@trustgaming3239
@trustgaming3239 5 лет назад
The problem is that your getpivot function doesn't always return the correct pivot. Not everyone will click that link to your github. You should fix that in the video
@vedicknowledge2361
@vedicknowledge2361 7 лет назад
not get answer properly
@oggiai
@oggiai 7 лет назад
+KOMAL MAGAR download the latest code from my GitHub site at www.github.com/joeyajames
@himanshup3720
@himanshup3720 4 года назад
too complicated you have made it
Далее