Hence the total time for mergeSort function will become n(log n + 1), which gives us a time complexity of O(n*log n). O(1).Īnd to merge the subarrays, made by dividing the original array of n elements, a running time of O(n) will be required. In this section we will understand why the running time for merge sort is O(n*log n).Īs we have already learned in Binary Search that whenever we divide a number into half in every step, it can be represented using a logarithmic function, which is log n and the number of steps can be represented by log n + 1(at most)Īlso, we perform a single step operation to find out the middle of any subarray, i.e. It is also a stable sort, which means the "equal" elements are ordered in the same order in the sorted list. Merge Sort is quite fast, and has a time complexity of O(n*log n). ![]() Let's consider an array with values as the array to be sorted.Ī = b // copying back the sorted list to a Now, the idea here is that an array with a single element is already sorted, so once we break the original array into subarrays which has only a single element, we have successfully broken down our problem into base problems.Īnd then we have to merge all these sorted subarrays, step by step to form one single sorted array. So we will break these subarrays into even smaller subarrays, until we have multiple subarrays with single element in them. In merge sort, we break the given array midway, for example if the original array had 6 elements, then merge sort will break it down into two subarrays with 3 elements each.īut breaking the orignal array into 2 smaller subarrays is not helping us in sorting the array. ![]()
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |