Advertisement
Guest User

Untitled

a guest
Apr 18th, 2015
205
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.32 KB | None | 0 0
  1. ####**MERGE\_SORT** :: Sorts the elements of ```array``` between ```start_index``` and ```final_index```, both inclussively
  2.  
  3. ```
  4. MERGE_SORT(array, start_index, final_index):
  5. IF start_index < final_index:
  6. middle_index = FLOOR((start_index + final_index)/2)
  7. MERGE_SORT(array, start_index, middle_index)
  8. MERGE_SORT(array, middle_index + 1, final_index)
  9. MERGE(array, start_index, middle_index, final_index)
  10. ```
  11.  
  12. _Find the middle index._
  13. _Distribute the sorting procedures in two smaller subset of arrays._
  14. _Once those two subset of arrays has been sorted, merge them to obtain the final set of sorted array._
  15.  
  16.  
  17. ####**MERGE** :: Merges two array in sorted order.
  18. The elements from ```start_index``` till ```middle_index``` is considered as _first array_ while the remaining i.e. the elements from ```middle_index + 1``` (**next to middle**), till ```final_index``` is considered as _Second array_
  19.  
  20. ```
  21. MERGE(array, start_index, middle_index, final_index):
  22. n1 = middle_index - start_index + 1 //size of first array
  23. n2 = final_index - middle_index //size of second array
  24.  
  25. //separate the arrays for easier comparison
  26. FOR i = 1 TO n1:
  27. FIRST_ARRAY = array[start_index + i - 1]
  28. FOR j = 1 TO n2:
  29. SECOND_ARRAY = array[middle_index +j]
  30.  
  31. // set the last elements to extremely high value.
  32. // in case the elements of that array expires, the value of other array elements will always be smaller to this value.
  33. // this value is also known by sentinal element.
  34. FIRST_ARRAY[n1 + 1] = INFINITY
  35. SECOND_ARRAY[n2 + 1] = INFINITY
  36.  
  37. i = 1 // keep track of FIRST_ARRAY
  38. j = 1 // keep track of SECOND_ARRAY
  39.  
  40. FOR k = start_index TO final_index
  41. IF FIRST_ARRAY[i] <= SECOND_ARRAY[j]
  42. array[k] = FIRST_ARRAY[i]
  43. i = i + 1
  44. ELSE
  45. array[k] = SECOND_ARRAY[j]
  46. j = j + 1
  47. ```
  48.  
  49. _Divide array (portion we are dealing with) in two separate arrays (first two FOR loops)._
  50. _Take two variables that points to the first element of each array (new ones)._
  51. _Compare the elements pointed by two pointers. Insert the smaller one into the array (old one) and increment its pointer such that it can point to next element in the array (refer to algorithm for MERGE, last FOR loop)._
  52. _The array ultimately obtained has the merged result of first and second array in sorted order._
  53.  
  54. - **Best Case:** _O(n log(n))_
  55. - **Average Case:** _O(n log(n))_
  56. - **Worst Case:** _O(n log(n))_
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement