Esempio n. 1
0
# Efficient for small data sets.
# Efficient for data sets that are already largely sorted.
# More efficient in practice than other simple quadratic algorithms
#  (e.g. selection sort, bubble sort).
# Stable - does not change the relative order of elements with equal keys.
# In-place - only requires a constant amount O(1) of additional memory.
# Online - can sort a list as it receives it.
#
## References:
#
# Introduction to Algorithms, section 2.1, page 16.
#
## Code:
#
import lib

def insertion_sort(data):
    for j in range(1, len(data)):
        key = data[j]
        # Insert data[j] into sorted sequence data[0..j-1].
        i = j - 1
        while i >= 0 and data[i] > key:
            data[i + 1] = data[i]
            i = i - 1
            data[i + 1] = key

    return data

if __name__ == "__main__":
    lib.test_array_sort(insertion_sort)
Esempio n. 2
0
            largest = left
        else:
            largest = i

        if right < heap_size and heap[right] > heap[largest]:
            largest = right

        if largest != i:
            heap[i], heap[largest] = heap[largest], heap[i]
            max_heapify(heap, heap_size, largest)

    # Input an array and build into a max heap.
    def build_max_heap(data):
        for i in range(len(data) / 2 - 1, -1, -1):
            max_heapify(data, len(data), i)

    # The first step: build the entire array into a max heap.
    build_max_heap(data)

    # The second step: Continuously remove the largest object from the
    # heap, and rebuild the max heap. Continue until there are no
    # objects left in the heap.
    for i in range(len(data) - 1, 0, -1):
        data[0], data[i] = data[i], data[0]
        max_heapify(data, i, 0)

    return data

if __name__ == "__main__":
    lib.test_array_sort(heap_sort)
Esempio n. 3
0
            if len(left) and len(right):
                if right[0] < left[0]:
                    sorted.append(right[0])
                    right.pop(0)
                else:
                    sorted.append(left[0])
                    left.pop(0)
            # Else append the remainder of either list:
            elif len(right):
                sorted += right
                right = []
            else:
                sorted += left
                left = []

        return sorted

    # A list of 1 element or an empty list is considered sorted.
    if len(data) <= 1:
        return data

    middle = int(len(data) / 2)
    left = merge_sort(data[:middle])
    right = merge_sort(data[middle:])

    return merge(left, right)


if __name__ == "__main__":
    lib.test_array_sort(merge_sort)