Тёмный

Python: MergeSort algorithm explained 

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

Merge Sort algorithm explained, and how to write a Merge Sort algorithm implementation in Python, includes example code.
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

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

 

10 сен 2024

Поделиться:

Ссылка:

Скачать:

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

Добавить в:

Мой плейлист
Посмотреть позже
Комментарии : 148   
@perfectMind91
@perfectMind91 7 лет назад
I am not sure if someone else pointed out to this problem earlier (didn't read all comments), but I had to change merge function, exactly I had to change the first 2 lines to the following: L = A[first:middle+1] R = A[middle+1:last+1] Otherwise if my array has an odd size it wouldn't correctly sort it. If you have a closer look at it it does make sense, in mergeSort function we included the middle element in the left part of the array but in merge function (because of python syntax) the middle element is included in the right side. Try this example: A = [4, 1, 5, 3, 7] to check. Thanks for the video.
@damcgrady388
@damcgrady388 5 лет назад
Yeah, the code is absolutely wrong and not Pythonic.
@rakhshandamujib2793
@rakhshandamujib2793 5 лет назад
You're a genius! I was struggling ever since time epoch! Jeez! Thank you!
@premchandupadhyay5817
@premchandupadhyay5817 5 лет назад
Thanks bro I was struggling too
@ayaatattar803
@ayaatattar803 5 лет назад
thanks! these changes work :)
@swaniketchowdhury
@swaniketchowdhury 5 лет назад
You are correct. It works
@billchen4923
@billchen4923 4 года назад
Joe explains merge sort so clearly, I got it. You are an awesome teacher.
@oggiai
@oggiai 4 года назад
Great to hear!
@uppubhai
@uppubhai 7 лет назад
Starting music feels a mission starting in cod modwen warfare
@JAt0m
@JAt0m 6 лет назад
Definitely unique among all those tuts.
@Razta_S
@Razta_S 3 года назад
im on a mission, to learn basic algorithms 10 hrs before an exam
@wotizit
@wotizit 5 месяцев назад
He knows we're all cramming and sleepy, legit wakes me up
@thatsjustjohn
@thatsjustjohn 5 лет назад
Using 999999999 is a very very poor decision for any programmer. Why would you not use the length to know the end of the list?
@oggiai
@oggiai 5 лет назад
Somewhat agree. Sentinel values are a widely used programming technique, not just invented by me. But list length would be better here.
@kylaxcry
@kylaxcry 5 лет назад
Or Inf
@chenzhenmei8831
@chenzhenmei8831 5 лет назад
@@oggiai , thanks for your video. I'm updating the merge function based on John's suggestion. def merge(A, first, mid, last): L = A[:mid] R = A[mid:] i = j = k = 0 while i < len(L) and j < len(R): if L[i] < R[j]: A[k] = L[i] i += 1 else: A[k] = R[j] j += 1 k += 1 while i < len(L): A[k] = L[i] i += 1 k += 1 while j < len(R): A[k] = R[j] j += 1 k += 1
@AhmadAfiqAzmi_xxnzonxx
@AhmadAfiqAzmi_xxnzonxx 4 года назад
@@chenzhenmei8831 can you explain what is this part do? while i < len(L): A[k] = L[i] i += 1 k += 1 while j < len(R): A[k] = R[j] j += 1 k += 1
@almuhimen8023
@almuhimen8023 4 года назад
@@AhmadAfiqAzmi_xxnzonxx This part is to make sure that there is no leftover in the array(both left and right)
@Sustainability-for-future
@Sustainability-for-future 4 года назад
I was reading my book by N.Miller and L Ranum for hours and hours. thanks for your 10min video it makes sense now. much easier to understand by watching a video rather than reading books. Top of it the English my second language...so your video helped me very much.
@kaushilkundalia2197
@kaushilkundalia2197 5 лет назад
After days or research, i wasn't able to fully understand merge sort. But all thanks to you sir, you made it very easy and clear ! Thanks a lot !!
@akash-kumar737
@akash-kumar737 Год назад
Always return to same video. Very well explained. Probably watching it for 10th time.
@rahmounioussama1624
@rahmounioussama1624 5 месяцев назад
thanks man, this is still valid for 2024
@piyushsharma417
@piyushsharma417 5 лет назад
Clear and concise explanation .The starting and ending sound is similar to 90's Bollywood action movies
@levix7859
@levix7859 5 лет назад
When separating arrays going to end, array(L) got slice L[first(0):middle(0)] = []!!!! You have to in calling merge add to middle + 1 ~ merge(A, first, middle + 1, last) or to slice add follow L[first: middle + 1] R[middle + 1:last + 1]
@nateF888
@nateF888 2 года назад
why did the merge function compare "1, 5, 6" already. Is it not supposed to compare "1" and "5" first then append the smaller number, then compare "5" to "6"?
@George-nx8zu
@George-nx8zu Месяц назад
Just found this about 9 years late. So am I understanding this correctly that the list is passed by reference and therefore can be mutated by any of the functions?
@AppleBoy4717
@AppleBoy4717 8 лет назад
Visual and clear. Helped me understand the concepts of sorting. Thank you, Joe. This is best explanation and explanation in python helps out a freshman in college.
@cbt121314
@cbt121314 4 года назад
can someone explain why appending a high number is necessary? I tried taking it off but that didn't work and I'm not sure I understand the reason behind appending it
@oggiai
@oggiai 4 года назад
It’s a technique for detecting the end of the list called Sentry Value. There are other ways of doing it too.
@mastermnd
@mastermnd 3 года назад
@@oggiai But HOW is it detecting the end of the list. Thats what we are missing
@Mr_Yod
@Mr_Yod 3 года назад
@@mastermnd Actually it doesn't: the algorithm just doesn't go past that number since it's something like float("inf") and every other number is smaller than that; besides, if we consider how the algorithm is made (for list_idx in range(first, last+ 1)), that number will never be put in the ordered list because the for loop will end before reaching that point.
@vincentluong6238
@vincentluong6238 6 лет назад
Using your videos and playlists to prep for interviews :). Great stuff
@rishabhkash5077
@rishabhkash5077 3 года назад
Good explaination but, would be great if you could mention that code is not correct Correction: L = arr[first:middle+1] R = arr[middle+1:last+1]
@hallvardstemshaug5979
@hallvardstemshaug5979 8 лет назад
This only seem to work for me with the parameters of the merge(_) method in merge_sort2(_) as: merge(A, first, *middle +1*, last). Currently it's: merge(A, first, middle, last), both in this video and on gitHub. The code on GitHub might seem to work, but it's because it uses a method from Quick Search when the list has less than 20 elements.
@oggiai
@oggiai 7 лет назад
Yes, you are right. I need to update my code on github. Will do soon.
@kuriku1
@kuriku1 6 лет назад
Is the code on github updated?
@MrPikulak
@MrPikulak 6 лет назад
Same, it doesn't work without your tweak
@asadullahfarooqi254
@asadullahfarooqi254 5 лет назад
@@MrPikulak thanks buddy. but will you please explain why it didn't work?
@kumark353
@kumark353 4 года назад
A methodical sort of the explanation before sorting. Very well explained
@josephbrown7502
@josephbrown7502 5 лет назад
Great explanation of merge sort! You really don't have to add a big faked number at the end tho, just a couple more if's will cover it: def merge(left, right, result): i = j = 0 for k in range(0, len(result)): if j >= len(right): result[k:len(result)] = left[i:len(left)] break elif i >= len(left): result[k:len(result)] = right[j:len(left)] break elif left[i] < right[j]: result[k] = left[i] i+=1 else: result[k] = right[j] j+=1
@DamienMurtagh-Galea
@DamienMurtagh-Galea 4 года назад
Hi Joe. Recursion is my kryptonite. I just watched your video on recursion for the factorials, and it made complete sense. I am confused here, because at no stage is any value returned to the next function up. What am I missing?
@oggiai
@oggiai 4 года назад
The values are returned when it reaches the base case. The function call stack keeps growing until the base case hits, then it works its way back down the call stack.
@faiza.s6509
@faiza.s6509 6 лет назад
Hi, i was looking at your code on github, and trying to understand it, one part specifically, when it says : def merge_sort2(A, first, last): if first < last: middle = (first + last)//2 merge_sort2(A, first, middle) merge_sort2(A, middle+1, last) merge(A, first, middle, last) this confused me because you used the function you were defining in the code in which you were defining it... wouldn't this just lead to an endless loop of the code repeating around that part, because it just repeats it endlessly and there's no "else:" part? That was really confusing could you please explain?
@owninggreendragsdude
@owninggreendragsdude 9 лет назад
Great explanation! Really helpful to see the code implemented as well. Subscribed.
@oggiai
@oggiai 9 лет назад
+owninggreendragsdude Thanks! Glad it was useful for you.
@priyasodhi
@priyasodhi 8 лет назад
I have tried the code in pyhton. But when i try to print the list generated by merge sort, the output that is coming is 'none'
@Dylan-vf6jx
@Dylan-vf6jx 6 лет назад
priya sodhi return it instead
@reccartoon
@reccartoon 5 лет назад
do this arr= ["your list elements"] merge_sort(arr) print(arr) i think this may help you
@tombranson9341
@tombranson9341 7 лет назад
I find these exercises great... they help get your 'mind' in order and thinking like a computer. I am working on both Python and Ruby programming, so I have been coding these in both languages... it's interesting that I have to make fine adjustments between the 2 since it's not 1:1... they're close however... not as distinct as if I were translating Python to C+ or Java. For example... I have been a little tricked up by Python's use of +1 or -1, which aren't necessarily needed in Ruby since it counts the exact number and we would place either two "periods" for including and three "periods" for up to and not including. Fun stuff, always helps.
@oggiai
@oggiai 7 лет назад
+Tom Branson good insights.
@tombranson9341
@tombranson9341 7 лет назад
Cool... for the folks having trouble... the programs work... I followed the videos and only for the quicksort did I have to resort to going to the GitHub link... since the final solution is not clear. I must say, the quicksort is one tough bastard to follow. I am going through it mentally, line-by-line... tough since you have to jump from function to function. These days newbies have all sort of created libraries and methods to do these things automatically almost, but I am sure that someone had to expend a lot of brain power to get this right the first time many moons ago... and sometimes magic sorting methods are just too magic... I like to lift the veil sometimes to learn more. I subscribed to your channel, Joe. Thanks
@annabelleellis8098
@annabelleellis8098 5 лет назад
i got an error and I was trying to use the github page and the page didn't load
@yashendratiwari7533
@yashendratiwari7533 5 лет назад
on giving input list as 12 34 1 6 2 to following code sorted list is not correct.Can someone figure out what is the mistake here code : def mergeSort(arr,start,end): middle = (start+end) // 2 if start < end : mergeSort(arr,start,middle) mergeSort(arr,middle+1,end) return merge(arr,start,middle,end) def merge(arr,start,middle,end): L = arr[start:middle] R = arr[middle:end+1] L.append(999999999) R.append(999999999) i = j = 0 for k in range(start,end+1): if L[i]
@xboxsucks12
@xboxsucks12 6 лет назад
What exactly puts the lists L & R in numerical order? If I had list[ 9, 5, 2, 3, 4, 7 ] and merge sorted to L[ 9, 5, 2] and R[ 3, 4, 7], wouldn't it sort to [ 3, 4, 7, 9, 5, 2] since it only moves to the next index in the L list once the 9 has been sorted? Thanks
@oggiai
@oggiai 6 лет назад
In your example, the L list would be split to call sort on [9, 5] and [2]. Then the returns from those sort calls would be in sorted order -- [5, 9], and [2] -- and they would be merged into [2, 5, 9]. You would never be merging L[ 9, 5, 2] and R[ 3, 4, 7] because L is not in sorted order, so it would continue breaking that down, then sorting as it merges them.
@prat534
@prat534 9 лет назад
Hi Joe James. I have a doubt (I might be wrong) do you think the formula for middle used in the merge_sort2 function is right ?. considering the first case, first = 0 and last = 7 leading to 3 instead of 4. Thank you for the explanation.
@oggiai
@oggiai 9 лет назад
+Pratheek Bangera very good question. Actually it doesn't matter. When you split an odd-sized list in half, either the left half will be larger or the right half will be. But you'll get exactly the same result either way. MergeSort will continue splitting each list in half until it gets to a list of size 1, then it starts merging. It doesn't care whether the left side is 1 bigger or smaller than the right side for the intermediate lists.
@prat534
@prat534 9 лет назад
+Joe James Thanks for the clarification Joe James. I will try this out now
@lukeelliott5921
@lukeelliott5921 5 лет назад
Since you are overwriting the input, you don't need a return statement?
@niteshrawat576
@niteshrawat576 4 года назад
Hi Joe, I can see a indexOutOfBound Exception if one of the list exhaust first. However your explainations and efforts really are great! Liking and subscribing to you sir!
@amol.jagdambe
@amol.jagdambe 3 года назад
yup. i got the same error
@amadrazo
@amadrazo 7 лет назад
Thanks MAN! Easy way to understand the algorithm.
@praneetkomandur6576
@praneetkomandur6576 3 месяца назад
why do we need to append the big 9999999 number what if we didn't? dont really understand that
@mohamedfayiz9348
@mohamedfayiz9348 25 дней назад
To find end of the list . there are many methods to find end of list
@andrelino4089
@andrelino4089 9 лет назад
I tried to do it (on the paper) with my own numbers and gave me incorrect. If i use [4,7,3,10,2,8] what would be the steps? PS: It gave me 2, 4, 3, 7, 8, 10
@andrelino4089
@andrelino4089 9 лет назад
André Lino Never mind! My bad! I figured it out!
@kunited9
@kunited9 3 года назад
Great video thanks
@davidandrejsin1259
@davidandrejsin1259 4 года назад
Question to the Python implementation. Every single implementation I have seen does not have a return statement. How are the results of the functions saved, if there's no return statement?
@oggiai
@oggiai 4 года назад
It’s an in-place sort, done on the original list, so there’s no return.
@davidandrejsin1259
@davidandrejsin1259 4 года назад
@@oggiai so does it mean that the sort is changing the order of the original array in real time? And if one was to write a merge sort with the return statement, would that create a new array instead of modifying the old one? It's mainly confusing for me because every pseudocode implemention of the merge sort always mentions the return statement and it also assigns each recursive code to a variable such as sorted_left = merge_sort(left_half) instead of only calling merge_sort(left_half).
@Mr_Yod
@Mr_Yod 3 года назад
@@davidandrejsin1259 Lists in python are mutable objects, so every action you do the list (even if it's inside a function) is done to the original list itself. With a return you'll have the function as a copy of the now-ordered list.
@xy0157
@xy0157 6 лет назад
some merge sorts, will break down the left side into individual elements writing them in order to memory, before separating elements in the left side.
@oggiai
@oggiai 6 лет назад
The method I presented is called "top-down" mergesort. There is also a "bottom-up" mergesort that is iterative rather than recursive. The both have the same performance.
@emaanmurtaza7431
@emaanmurtaza7431 2 года назад
here is the right code import sys def merge_sort(A): merge_sort2(A, 0, len(A)-1) def merge_sort2(A, first, last): if first < last: middle = (first + last)//2 merge_sort2(A, first, middle) merge_sort2(A, middle+1, last) merge(A, first, middle, last) def merge(A, first, middle, last): L = A[first:middle+1] R = A[middle+1:last+1] L.append(sys.maxsize) R.append(sys.maxsize) i = j = 0 for k in range (first, last+1): if L[i]
@orangetinyterrors
@orangetinyterrors 8 лет назад
I'd recommend doing some clean up... Using the sentinel value, for example, is just not necessary. In other places it's somewhat odd to me to give or take 1. I think by reworking what "last" represents you can drop most of those corrections. That is, consider using the range [first, last) rather than [first, last] and just passing len(A) to merge_sort2 instead of len(A) - 1. (This will change the condition left < right to left < right - 1 but the recursive calls no longer have to use middle + 1, for the ranges [first, middle) and [middle, last).
@B3SSPR0
@B3SSPR0 4 года назад
In a real world scenario, when does it make sense to manually recreate these algorithms in code rather use their builtin implementation. For example, why would I manually write a merge sort algorithm rather than use Python's sort() method?
@oggiai
@oggiai 4 года назад
Honestly, probably never. But there is value in learning how sorting algorithms work. You will have to write your own algorithms often, and learning a variety of basic sorting and graph traversal algos will help prepare you to do that. It’s a fundamental of computer science so you can understand more advanced programs. Data structures and algorithms are also the hottest topics for job interviews to test your skills. Believe it. I got a job offer from ETrade because I could explain how balanced trees work.
@railroadman2k
@railroadman2k 4 года назад
Because all companies out of their mind on the algorithms solving. So we need to deal with it
@I-just-hold-white-paper-up
@I-just-hold-white-paper-up 6 лет назад
Thanks for your help, Now I have a question, why do you append sys.maxsize after L and R? I have tried without sys.maxsize, it cannot be compiled, can you explain why?
@oggiai
@oggiai 6 лет назад
It’s just sentinel values to detect the end of the list. There are other ways of detecting the end of a list if you don’t like this method.
@I-just-hold-white-paper-up
@I-just-hold-white-paper-up 6 лет назад
Joe James This method is cool but I don't know why it is necessary to know the end of the list and why the sentinel value can help system to detect the end
@cenovoa21
@cenovoa21 2 года назад
@@I-just-hold-white-paper-up I was wondering the same. It appears to me like the sentinel values are there to act as a visual clue for the sake of debugging. They can be manually changed to something like 99 or 999 and it still works. If I'm not mistaken, they act as padding to the lists so as to prevent a 'list index out of range' error. Also, the last iteration pops the remaining right item onto the final list. I see this question was asked 4 years ago, but maybe it'll help someone else...
@alialsabbah5511
@alialsabbah5511 5 лет назад
Link in description is broken. Here's the code. github.com/joeyajames/Python/blob/master/Sorting%20Algorithms/merge_sort.py
@shaked7062
@shaked7062 6 лет назад
thanks helped a lot! :)
@RaoWaqrAkram
@RaoWaqrAkram 5 лет назад
its going on infinite. .... mergesort(A,first,mid) in mergesort2() is not correct
@ashishranjan9145
@ashishranjan9145 4 года назад
l.append (999999999) why so...plz explain me in very easy words....so that i can get it...
@oggiai
@oggiai 4 года назад
That’s just a sentinel value to detect the end of each list.
@aravindmurali3427
@aravindmurali3427 5 лет назад
The code is @ github.com/joeyajames/Python/blob/master/Sorting%20Algorithms/merge_sort.py
@c-spam9581
@c-spam9581 7 лет назад
I understand that you teach computer science and therefore teach a lot of theory, but I am still a little confused. Is there a reason why someone may need to roll their own sorting algorithm over using the built in sort function? It's interesting to learn how these work, but if I need to sort something, wouldn't I use the built in sort function most of the time? I'm interested in studying this because it seems like it would be useful for an interview, but what about actual application? Where would a normal dev use this?
@oggiai
@oggiai 7 лет назад
+C-SPAM you're 100% right. You will rarely if ever need to write your own sorting algorithms. Nearly every language has built in sorting that is faster than any algorithm you write. CS students learn to write sorting algorithms mainly as a learning tool, not only to learn how sorting algorithms work but also to learn to use Big O to analyze and compare performance of different algorithms.
@c-spam9581
@c-spam9581 7 лет назад
I understand the purpose behind videos like these after watching your video on hash tables, which was a great one by the way. Thank you for sharing these!
@abadidibadou5476
@abadidibadou5476 4 года назад
@@c-spam9581 sorting algorithms are typical interview questions to check your abstract thinking......this is maybe a very late response
@HimanshuYadav-bt4zk
@HimanshuYadav-bt4zk 5 лет назад
code is not present on github
@jimmygan801
@jimmygan801 Год назад
you da champ
@kuriku1
@kuriku1 6 лет назад
I'm trying to use this code for a text file with strings and it doesn't work...
@oggiai
@oggiai 6 лет назад
Did you retype the code from the video, or did you download it from GitHub?
@kuriku1
@kuriku1 6 лет назад
From github, my problem is I'm sorting a text file of random strings and I'm using merge sort to sort them and I get and error on the if L[i]
@oggiai
@oggiai 6 лет назад
I see. You can use
@kuriku1
@kuriku1 6 лет назад
Yes very true, thanks for the video.
@I4mSanjay
@I4mSanjay 5 лет назад
I don't think this program works correctly because you are not returning merged data to merge_sort2() function.
@oggiai
@oggiai 5 лет назад
Please try downloading and testing my code, then if you find bugs please try to provide relevant line numbers and I’ll check it out.
@elliotwilens4859
@elliotwilens4859 3 года назад
Was great until the end, could have tied it all together really nicely. Well-explained concept, though.
@jadehockenhull7883
@jadehockenhull7883 7 лет назад
Joe helpWhy do we need to use 99999999999 instead of 'N' to know when we have reached the end of the list
@oggiai
@oggiai 7 лет назад
+KilljoyWithWhiskers 123 using 999999 is not a very elegant solution to be honest. I used it here because it's easy to follow. In practice I would use sys.maxsize or something like that.
@jadehockenhull7883
@jadehockenhull7883 7 лет назад
Alright, thank you! We're GCSE Computer Science students using your videos to help us grasp the subject! :)
@Mr_Yod
@Mr_Yod 3 года назад
@@oggiai float("inf") maybe? So there's no need to import sys
@raquelmelo3788
@raquelmelo3788 8 лет назад
if L[i]
@oggiai
@oggiai 8 лет назад
+Raquel Melo you might try copying the code directly from my github site to make sure you don't have any typing or indention errors. If you get the same error then let me know what input list you're using and I'll check it out.
@ShubhamKumar-gd4sn
@ShubhamKumar-gd4sn 5 лет назад
Well the code is not working
@oggiai
@oggiai 5 лет назад
Did you retype the code from the video or download it from my GitHub site? I recommend getting the latest code from GitHub. If you copied and pasted any code you could have a mix of tabs and spaces for indents, so you should view hidden characters to check that. Also, this was written and tested in Python 3. If you are using Python 2 you may get errors. If none of these tips helps then tell me more about your error message and/or post your code.
@ShubhamKumar-gd4sn
@ShubhamKumar-gd4sn 5 лет назад
@@oggiai Thanks for response and code is working now i had just created a small mistake while typing
@marcelomelo6349
@marcelomelo6349 8 месяцев назад
def merge_sort(iterable: list): cont = 0 if len(iterable) % 2 == 0: new_iterable = [[i] if not isinstance(i, list) else i for i in iterable] else: new_iterable = [[i] if not isinstance(i, list) else i for i in iterable] new_iterable[-2].append(new_iterable[-1][0]) del new_iterable[-1] for i in range(0, len(new_iterable), 2): for j in range(len(new_iterable[cont + 1])): new_iterable[cont].sort() new_iterable[cont + 1].sort() new_iterable[cont].append(new_iterable[cont + 1][j]) cont += 1 del new_iterable[cont] if len(new_iterable) == 1: return new_iterable[0] return merge_sort(new_iterable)
@marcelomelo6349
@marcelomelo6349 8 месяцев назад
If you want to see the process: def merge_sort(iterable: list): cont = 0 if len(iterable) % 2 == 0: new_iterable = [[i] if not isinstance(i, list) else i for i in iterable] else: new_iterable = [[i] if not isinstance(i, list) else i for i in iterable] new_iterable[-2].append(new_iterable[-1][0]) del new_iterable[-1] print(new_iterable) for i in range(0, len(new_iterable), 2): for j in range(len(new_iterable[cont + 1])): new_iterable[cont].sort() new_iterable[cont + 1].sort() new_iterable[cont].append(new_iterable[cont + 1][j]) cont += 1 del new_iterable[cont] print(new_iterable) if len(new_iterable) == 1: return new_iterable[0] return merge_sort(new_iterable)
@carlknightcoph9494
@carlknightcoph9494 5 лет назад
how about just add all the arrays and sort it .
@kerodfresenbetgebremedhin1881
@kerodfresenbetgebremedhin1881 5 лет назад
what if there is a number greater than 99999999 in the list, lol
@jerrychan3055
@jerrychan3055 5 лет назад
use float('inf') instead
@bavidlynx3409
@bavidlynx3409 4 года назад
Jerry Chan could you explain it a little more?
@Mr_Yod
@Mr_Yod 3 года назад
@@bavidlynx3409 float("inf") creates an infinite (or at least a value that the compiler interpret as infinite), so every other number you compare with it is by default smaller.
@chungtinlong
@chungtinlong 8 лет назад
Whole thing was good until the pile of 9's. Fairly sure the 'very large value' part is ghettocode that has more theoretically correct alternatives. And honestly, it's confusing to have the extra values too.
@oggiai
@oggiai 8 лет назад
Not meant to be production code, it's educational to help people learn how the algorithm works. Yes, Python 3 has sys.maxsize that may be more appropriate. But hopefully this video is significantly clearer and easier to follow than most other MergeSort videos you'll see so you can actually learn how mergesort works and how it can be implemented. Not to brag, but I don't see ANY other videos doing this.
@semirumutkurt6635
@semirumutkurt6635 8 лет назад
L=alist[first:middle] R=alist[middle:last+1] instead it would be better L=alist[:middle] R=[middle:] there could be done editions in the same logic with above. And I'm also getting index error
@semirumutkurt6635
@semirumutkurt6635 8 лет назад
for instance in one list, there might be all items lesser than other list items. So in this case, increment will happened in just one array and in the end it will go out of list's index range. So we have to limit j and k.
@oggiai
@oggiai 8 лет назад
The way I wrote it works fine, and you can download my code from my github site if you want. Of course there are other ways to implement MergeSort. The reason your suggestion doesn't work with my implementation is that my implementation allows you to sort items 500 to 1000 of a 1M item list if you want. And with MergeSort you do need to make recursive calls on sublists of the main list, which I did by keeping 1 main list and passing as arguments the first and last index. Like I said, there are many other ways to do it. I encourage you to tinker with my code all you like.
@semirumutkurt6635
@semirumutkurt6635 8 лет назад
Thanks
@MarttyLovato
@MarttyLovato 5 лет назад
no entendí nada tío
@oggiai
@oggiai 5 лет назад
Es porque necessito traducirla en espanol? Or es demasiado complejo?
@MarttyLovato
@MarttyLovato 5 лет назад
@@oggiai no, don't worry i'm just a beginner and theres some things i dont understand yet!! but your video is actually good, don't mind me!!!
@loganbourne3865
@loganbourne3865 5 лет назад
list.sort()
@oggiai
@oggiai 5 лет назад
Yes, that’s easier and works better, but it won’t help you much in a Google interview if they decide to drill you on algorithms.
@abadidibadou5476
@abadidibadou5476 4 года назад
@@oggiai you can avoid appending 99999 by checking i and j values
@Mr_Yod
@Mr_Yod 3 года назад
@@abadidibadou5476 Yes, but increasing if statements slows the algorithm.
@billchen4923
@billchen4923 4 года назад
You code is not correct, I tested it, the correct code should be like this: L = arr[first:middle+1] R = arr[middle+1:last+1]
Далее
Python: QuickSort algorithm explained
8:33
Просмотров 113 тыс.
10 Sorting Algorithms Easily Explained
10:48
Просмотров 55 тыс.
Sigma Girl Pizza #funny #memes #comedy
00:14
Просмотров 1,7 млн
10 FORBIDDEN Sorting Algorithms
9:41
Просмотров 854 тыс.
Merge Sort In Python Explained (With Example And Code)
13:35
Merge sort algorithm
18:20
Просмотров 2,2 млн
5 Useful F-String Tricks In Python
10:02
Просмотров 303 тыс.
Sorting Algorithms Explained Visually
9:01
Просмотров 533 тыс.
Learn Merge Sort in 13 minutes 🔪
13:45
Просмотров 293 тыс.
Python Decorators in 15 Minutes
15:14
Просмотров 440 тыс.
Sigma Girl Pizza #funny #memes #comedy
00:14
Просмотров 1,7 млн