Sorting

    Timsort

    Just use [8,2,4,10].sort()

    Mergesort

    def merge_sort(unsorted_list):
       if len(unsorted_list) <= 1:
          return unsorted_list
    
       middle = len(unsorted_list) // 2
       left_list = unsorted_list[:middle]
       right_list = unsorted_list[middle:]
    
       left_list = merge_sort(left_list)
       right_list = merge_sort(right_list)
    
       return list(_merge_sort_merge(left_list, right_list))
    
    def _merge_sort_merge(left_half, right_half):
       result = []
    
       while len(left_half) != 0 and len(right_half) != 0:
          if left_half[0] < right_half[0]:
             result.append(left_half[0])
             left_half.remove(left_half[0])
          else:
             result.append(right_half[0])
             right_half.remove(right_half[0])
    
       if len(left_half) == 0:
          result = result + right_half
       else:
          result = result + left_half
    
       return result
    

    source

    Quicksort

    def _quick_sort_partition(arr, low, high):
        i = (low-1)
        pivot = arr[high]
    
        for j in range(low, high):
            if arr[j] <= pivot:
                i = i+1
                arr[i], arr[j] = arr[j], arr[i]
    
        arr[i+1], arr[high] = arr[high], arr[i+1]
        return (i+1)
    
    def quick_sort(arr, low, high):
        if len(arr) == 1:
            return arr
    
        if low < high:
            pi = _quick_sort_partition(arr, low, high)
    
            quick_sort(arr, low, pi-1)
            quick_sort(arr, pi+1, high)
    

    source

    Bubblesort

    def bubble_sort(unsorted_list):
       for iter_num in range(len(unsorted_list)-1, 0, -1):
          for index in range(iter_num):
             if unsorted_list[index] > unsorted_list[index + 1]:
                tmp = unsorted_list[index]
                unsorted_list[index] = unsorted_list[index + 1]
                unsorted_list[index + 1] = tmp
    

    source