Example #1
0
from utils import mock, screen, used_time


def selection_sort(array):
    """
    选择排序算法
    复杂度: O(n^2)
    思路:
        遍历数组,在遍历过程中按索引从小到大依次排序,每次排序将从没有排序的部分取中出最小值与当前应排序位置数据进行交换。
    """
    for index in xrange(len(array)):  # 遍历数组
        min_index = index  # 存储每一轮排序的最小值
        for j in xrange(index, len(array)):  # 遍历未排序部分
            if array[j] < array[min_index]:  # 找出未排序部分最小值
                min_index = j
        array[min_index], array[index] = array[index], array[min_index]  # 将最小值与排序位置值进行交换


if __name__ == '__main__':
    # 对算法进行可视化
    screen.draw_sorting(selection_sort)

    # 对对象列表进行选择排序
    exam_results = mock.sample_exam_results(80)
    screen.print_array(exam_results, '排序前')
    selection_sort(exam_results)
    screen.print_array(exam_results, '排序后')

    # 测试用时
    print '排序10000个数字耗时:', used_time(selection_sort, num=10000)
Example #2
0

        5 8 0 2 1 6 3 9  # 按最底层分组进行归并
        A A A A B B B B
        a a b b c c d d


        0 2 5 8 1 3 6 9  # 继续归并
        A A A A B B B B


        0 1 2 3 5 6 8 9  # 归并完最顶层的分组后,排序完成

    """

    __merge_sort(array, 0, len(array))


if __name__ == '__main__':
    # 对算法进行可视化
    screen.draw_sorting(merge_sort, interval=0.1)

    # 对对象列表进行选择排序
    exam_results = mock.sample_exam_results(9)
    screen.print_array(exam_results, '排序前')
    merge_sort(exam_results)
    screen.print_array(exam_results, '排序后')

    # 测试用时
    print '排序10000个数字耗时:', used_time(merge_sort, num=10000)
Example #3
0
        在插入时从后往前比较,若不是最终位置则向后复制一份当前比较位置的数据,而不是与排序值进行交换。
    """
    for index in xrange(1, len(array)):  # 遍历数组无序部分
        temp = array[index]  # 备份当前要插入的数据
        for j in reversed(xrange(index)):  # 倒序遍历数组有序部分
            if temp < array[j]:  # 判断当前元素是否大于有序部分的某一个元素
                array[j + 1] = array[j]  # index前比temp大的元素后移一位
                if j == 0:  # 如果已到达第一个元素,说明当前数据在有序部分最小,直接放在开始位置
                    array[0] = temp
                    break  # 插入完成后结束本次遍历
            else:  # 如果有序部分的一个数比要插入的数据小,就将要插入的数据排在他后面
                array[j + 1] = temp
                break  # 插入完成后结束本次遍历


if __name__ == '__main__':
    # 对算法进行可视化
    screen.draw_sorting(insertion_sort_plus,
                        interval=1,
                        frame_frequency=0.5,
                        tag_num=1)

    # 对对象列表进行选择排序
    exam_results = mock.sample_exam_results(8)
    screen.print_array(exam_results, '排序前')
    insertion_sort_plus(exam_results)
    screen.print_array(exam_results, '排序后')

    # 测试用时
    print '排序10000个数字耗时:', used_time(insertion_sort_plus, num=10000)