经典排序算法的Python实现
Posted MKYAN
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了经典排序算法的Python实现相关的知识,希望对你有一定的参考价值。
一、选择排序select_sort
# Finds the smallest value in an array def findSmallest(arr): # Stores the smallest value smallest = arr[0] # Stores the index of the smallest value smallest_index = 0 for i in range(1, len(arr)): if arr[i] < smallest: smallest = arr[i] smallest_index = i return smallest_index # Sort array def selectionSort(arr): newArr = [] for i in range(len(arr)): # Finds the smallest element in the array and adds it to the new array smallest = findSmallest(arr) newArr.append(arr.pop(smallest)) return newArr print selectionSort([5, 3, 6, 2, 10])
一、快速排序quick_sort
def quicksort(array): if len(array) < 2: # base case, arrays with 0 or 1 element are already "sorted" return array else: # recursive case pivot = array[0] # sub-array of all the elements less than the pivot less = [i for i in array[1:] if i <= pivot] # sub-array of all the elements greater than the pivot greater = [i for i in array[1:] if i > pivot] return quicksort(less) + [pivot] + quicksort(greater) print quicksort([10, 5, 2, 3])
以上是关于经典排序算法的Python实现的主要内容,如果未能解决你的问题,请参考以下文章