Sort _ Python

# sort algorthim

# insert sort algorthim O(n.^2)

def InsertSort(s):
    for i in range(0, len(s)):
        for j in range(i + 1, len(s)):
            if s[i] > s[j]:
                temp = s[i]
                s[i] = s[j]
                s[j] = temp


# buble sort algorthim O(n.^2)

def BubleSort(s):
    for i in range(0, len(s)):
        for j in range(0, len(s) - i - 1):
            if s[j] > s[j + 1]:
                temp = s[j + 1]
                s[j + 1] = s[j]
                s[j] = temp
                print(s)

# MergeSort algorthim O(nlogn) n: the sum of elements in the list

# divid list into half
# continue until we have single list
# merge of the sublists

def Merge(low, high):
    result = []  # empty list
    i, j = 0, 0
    while (i < len(low) and j < len(high)): 
        if (low[i] <= high[j]):
            result.append(low[i])
            i += 1 
        else:
            result.append(high[j])
            j += 1
    while (i < len(low)):
        result.append(low[i])
        i += 1
    while (j < len(high)):
        result.append(high[j])
        j += 1
    print(low, high)
    return result


def MergeSort(s):
    if len(s) < 2:
        return s
    else:
        nMid = len(s) / 2
        mid = int(nMid)
        low = MergeSort(s[:mid])
        high = MergeSort(s[mid:])
        return Merge(low, high)

你可能感兴趣的:(Sort _ Python)