Python Example – Write a Python program to sort a list of elements using Time sort

Hits: 8

(Python Example for Citizen Data Scientist & Business Analyst)


Write a Python program to sort a list of elements using Time sort.


Sample Solution:

Python Code:

def binary_search(lst, item, start, end):
    if start == end:
        if lst[start] > item:
            return start
            return start + 1
    if start > end:
        return start

    mid = (start + end) // 2
    if lst[mid] < item:
        return binary_search(lst, item, mid + 1, end)
    elif lst[mid] > item:
        return binary_search(lst, item, start, mid - 1)
        return mid

def insertion_sort(lst):
    length = len(lst)

    for index in range(1, length):
        value = lst[index]
        pos = binary_search(lst, value, 0, index - 1)
        lst = lst[:pos] + [value] + lst[pos:index] + lst[index+1:]
    return lst

def merge(left, right):
    if not left:
        return right

    if not right:
        return left

    if left[0] < right[0]:
        return [left[0]] + merge(left[1:], right)

    return [right[0]] + merge(left, right[1:])

def time_sort(lst):
    runs, sorted_runs = [], []
    length = len(lst)
    new_run = [lst[0]]
    sorted_array = []

    for i in range(1, length):
        if i == length - 1:

        if lst[i] < lst[i - 1]:
            if not new_run:
                runs.append([lst[i - 1]])
                new_run = []

    for run in runs:

    for run in sorted_runs:
        sorted_array = merge(sorted_array, run)

    return sorted_array

user_input = input("Input numbers separated by a comma:n").strip()
nums = [int(item) for item in user_input.split(',')]

Sample Output:

Input numbers separated by a comma:
25, 45, 69, 79, 23
[23, 25, 45, 69, 79]


Write a Python program to sort a list of elements using Time sort

Sign up to get end-to-end “Learn By Coding” example.

Disclaimer: The information and code presented within this recipe/tutorial is only for educational and coaching purposes for beginners and developers. Anyone can practice and apply the recipe/tutorial presented here, but the reader is taking full responsibility for his/her actions. The author (content curator) of this recipe (code / program) has made every effort to ensure the accuracy of the information was correct at time of publication. The author (content curator) does not assume and hereby disclaims any liability to any party for any loss, damage, or disruption caused by errors or omissions, whether such errors or omissions result from accident, negligence, or any other cause. The information presented here could also be found in public knowledge domains.