Advertisement
VikkaLorel

mergeSort

May 31st, 2018
269
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.14 KB | None | 0 0
  1. #!/usr/bin/env python3
  2.  
  3.  
  4. def e_cmp(element_1: int, element_2: int, descend: bool = False) -> bool:
  5.     """
  6.    Compare the value of the two input value.
  7.    :rtype: bool
  8.    :param element_1:
  9.    :param element_2:
  10.    :param descend:
  11.    :return:
  12.    """
  13.     if descend:
  14.         return element_1 > element_2
  15.     else:
  16.         return element_1 <= element_2
  17.  
  18.  
  19. def merge(list1: list, list2: list, descend: bool = False) -> list:
  20.     """
  21.    Sort 2 lists by merging in ascending (descend == True)
  22.    or descending (descend == False) order.
  23.    :rtype: list
  24.    :param list1:
  25.    :param list2:
  26.    :param descend:
  27.    :return:
  28.    """
  29.     iter1, iter2 = 0, 0
  30.     result = list()
  31.     while (iter1 < len(list1)) & (iter2 < len(list2)):
  32.         if e_cmp(list1[iter1], list2[iter2], descend):
  33.             result.append(list1[iter1])
  34.             iter1 += 1
  35.         else:
  36.             result.append(list2[iter2])
  37.             iter2 += 1
  38.     if list1:
  39.         result.extend(list1[iter1:])
  40.     if list2:
  41.         result.extend(list2[iter2:])
  42.     return result
  43.  
  44.  
  45. def merge_split(origin_list: list, descend: bool = False) -> list:
  46.     """
  47.    Construct the correct call architecture of
  48.    merge in ascending (descend == true)
  49.    or descending (descend != 1) order.
  50.    :rtype: list
  51.    :param origin_list:
  52.    :param descend:
  53.    :return:
  54.    """
  55.     if len(origin_list) <= 1:
  56.         return origin_list
  57.     tmp_list = list()
  58.     new_list = list()
  59.     for e in origin_list:
  60.         tmp_list.append(e)
  61.         if len(tmp_list) >= 2:
  62.             new_list.append(merge(tmp_list[0], tmp_list[1], descend))
  63.             tmp_list = list()
  64.     if tmp_list:
  65.         new_list.append(merge(tmp_list[0], [], descend))
  66.     return merge_split(new_list, descend)
  67.  
  68.  
  69. def merge_sort(origin_list: list, descend: bool = False) -> list:
  70.     """
  71.    Split the array into as many array that the original array
  72.    contain then call the mergeSplit function.
  73.    :rtype: list
  74.    :param origin_list:
  75.    :param descend:
  76.    :return:
  77.    """
  78.     result = list()
  79.     for e in origin_list:
  80.         result.append([e])
  81.     return merge_split(result, descend)[0]
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement