选择排序和冒泡排序的Python实现

最近翻阅一些算法书籍,决定用Python实现一些简单的算法,并在博客上做下学习记录,本次记录的是选择排序和冒泡排序。

选择排序

import numpy as np

arr = np.arange(10)
np.random.shuffle(arr)
list = arr.tolist()
print(list)

def selectSort(list):
    for i in range(len(list)-1):
        smallest = list[i]
        for j in range(i+1, len(list)):
            if smallest > list[j]:
                temp = list[j]
                list[j] = smallest
                smallest = temp
        list[i] = smallest
    return list

print(selectSort(list))

冒泡排序

import numpy as np

arr = np.arange(10)
np.random.shuffle(arr)
list = arr.tolist()
print(list)

def bubbleSort(list):
    for i in range(1, len(list)):
        for j in range(0, len(list)-i):
            if list[j] > list[j+1]:
                temp = list[j+1]
                list[j+1] = list[j]
                list[j] = temp
    return list

print(bubbleSort(list))