Example #1
0
#!/usr/bin/env python

from sorting_tests import test

def quicksort(list):
    # Lists of length 1 or 0 are trivially sorted
    if len(list) <= 1:
        return list

    # Break the list into two smaller lists by comparing each value with the first element in the list, called the pivot. 
    pivot = list[0]
    lteq_list = []
    gt_list = []

    for i in list[1:]:
        if i <= pivot:
            lteq_list.append(i)
        else:
            gt_list.append(i)
    
    return quicksort(lteq_list) + [pivot] + quicksort(gt_list)

if __name__ == "__main__":
    test(quicksort)
Example #2
0
            if left_list[0] < right_list[0]:
                sorted_list.append(left_list[0])
                left_list = left_list[1:]
            else:
                sorted_list.append(right_list[0])
                right_list = right_list[1:]
        elif len(left_list) > 0:
            sorted_list.append(left_list[0])
            left_list = left_list[1:]
        else:  # right_list nonempty
            sorted_list.append(right_list[0])
            right_list = right_list[1:]
    return sorted_list


def mergesort(list):
    # Lists of length <= 1 are trivially sorted
    if len(list) <= 1:
        return list

    # Split the list in half and sort each side
    left_list = mergesort(list[0 : len(list) / 2])
    right_list = mergesort(list[len(list) / 2 :])

    # Merge the newly sorted lists
    return merge(left_list, right_list)


if __name__ == "__main__":
    test(mergesort)
Example #3
0
#!/usr/bin/env python

from sorting_tests import test

def heapsort(list):
    return list



if __name__ == "__main__":
    test(heapsort)
Example #4
0
#!/usr/bin/env python

from sorting_tests import test

def bubble_sort(list):
    swaps_happened = True
    while swaps_happened:
        swaps_happened = False
        for i in range(0, len(list)-1):
            if (list[i] > list[i+1]):
                swap = list[i+1]
                list[i+1] = list[i]
                list[i] = swap
                swaps_happened = True
    return list

if __name__ == "__main__":
    test(bubble_sort)