Python3 三种排序 冒泡排序 选择排序 插入排序

Python3 三种排序 冒泡排序 选择排序 插入排序

冒泡排序

从头开始两个满足条件的相邻数交换,这样一次之后的最大值就放在了最后,冒泡的范围减一。

def bubble_sort(nums):
    for i in range(len(nums) - 1):  
        for j in range(len(nums) - i - 1):  
            if nums[j] > nums[j + 1]:
                nums[j], nums[j + 1] = nums[j + 1], nums[j]
    return nums
    
bubble_sort([9,3,6,5,3]) 
'''
[3, 9, 6, 5, 3]
[3, 6, 9, 5, 3]
[3, 6, 5, 9, 3]
[3, 6, 5, 3, 9]
[3, 6, 5, 3, 9]
[3, 5, 6, 3, 9]
[3, 5, 3, 6, 9]
[3, 5, 3, 6, 9]
[3, 3, 5, 6, 9]
[3, 3, 5, 6, 9]
'''

选择排序

每次从未排序区选个最大值与当前坐标的值交换。

def selection_sort(nums):
    for i in range(len(nums)-1, 0, -1):
        nums[i] , nums[nums.index(max(nums[:i+1]))] = nums[nums.index(max(nums[:i+1]))] , nums[i]
    return nums
    
selection_sort([9,3,6,5,3]) 
'''
[3, 3, 6, 5, 9]
[3, 3, 5, 6, 9]
[3, 3, 5, 6, 9]
[3, 3, 5, 6, 9]
'''

插入排序

从未排序区 选一个值 插入到已排序区的合适位置。

def insertion_sort(nums):
    for i in range(1, len(nums)): 
        for j in range(i, 0, -1):
            if nums[j] < nums[j-1]:
                nums[j], nums[j-1] = nums[j-1], nums[j]  
    return nums
    
insertion_sort([9,3,6,5,3])
'''
[3, 9, 6, 5, 3]
[3, 6, 9, 5, 3]
[3, 5, 6, 9, 3]
[3, 3, 5, 6, 9]
'''

分享到 :
相关推荐

Leave a Reply

Your email address will not be published. Required fields are marked *