码迷,mamicode.com
首页 > 编程语言 > 详细

基本排序-冒泡/选择/插入(python)

时间:2019-07-10 23:10:54      阅读:217      评论:0      收藏:0      [点我收藏+]

标签:基本   shuf   imp   排序   for   random   shu   col   style   

# -*- coding: utf-8 -*-


import random

def bubble_sort(seq):  
    n = len(seq)
    for i in range(n-1):
        print(seq)    
        for j in range(n-1-i):  
            if seq[j] > seq[j+1]:
                seq[j], seq[j+1] = seq[j+1], seq[j]
        print(seq)


def test_bubble_sort():
    seq = list(range(10))  
    random.shuffle(seq)   
    sorted_seq = sorted(seq) 
    bubble_sort(seq)
    assert seq == sorted_seq


def select_sort(seq):
    n = len(seq)
    for i in range(n-1):
        min_idx = i    
        for j in range(i+1, n):    
            if seq[j] < seq[min_idx]:
                min_idx = j    
        if min_idx != i:    
            seq[i], seq[min_idx] = seq[min_idx], seq[i]


def test_select_sort():
    seq = list(range(10))
    random.shuffle(seq)
    sorted_seq = sorted(seq)
    select_sort(seq)
    assert seq == sorted_seq


def insertion_sort(seq):
    n = len(seq)
    print(seq)
    for i in range(1, n):
        value = seq[i]    
        pos = i
        while pos > 0 and value < seq[pos-1]:
            seq[pos] = seq[pos-1]  
            pos -= 1
        seq[pos] = value  
        print(seq)

 

基本排序-冒泡/选择/插入(python)

标签:基本   shuf   imp   排序   for   random   shu   col   style   

原文地址:https://www.cnblogs.com/muzinan110/p/11166993.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!