选择排序&快速排序示例

1,选择排序简单示例(python实现)

def findSmallest(arr):
    smallest = arr[0]
    smallest_index = 0
    for i in range(1,len(arr)):
        if arr[i] < smallest:
            smallest = arr[i]
            smallest_index = i
    return smallest_index    
#sort the array
def selectSort(arr):
    newArr = []
    for i in range(1,len(arr)):
        smallest_index = findSmallest(arr)
        newArr.append(arr.pop(smallest_index))#删去原始序列中的最小值并添加进入newArr
    return newArr                      
arr = [1,6,8,3,2,5,10]
print(selectSort(arr))

注:选择排序需要一遍又一遍的检查原始序列元素,检查次数依次为n,n-1,…,1。完成排序时检车总次数为(1+n)*n/2,算法复杂度为O(n^2)

2,快速排序简单示例(python实现)

def quicksort(array):
    if len(array) < 2:
        return array
    else:
        pivot = array[0] #pivot为基准值,中文为枢纽的意思
        less = []
        greater = []
        for i in array[1:]:
            if i <= pivot:
                less += [i]
            else:
                greater += [i]
    return quicksort(less) + [pivot] + quicksort(greater)
arr = [1,9,5,3,7]
print(quicksort(arr))
def quicksort(array):
    if len(array) < 2:
        return array
    else:
        pivot = array[0] #pivot为基准值,中文为枢纽的意思
        less = [i for i in array[1:] if i <= pivot]
        greater = [i for i in array[1:] if i > pivot]
    return quicksort(less) + [pivot] + quicksort(greater)
arr = [1,9,5,3,7]
print(quicksort(arr))

注:快速排序需要先随机选取一个基准值pivot,然后通过这个值将数列分为两个部分,再分别对两部分采用相同的方式进行迭代排序,分而治之(divide and conquer)。

你可能感兴趣的:(笔记,python,排序算法)