在去公司面试的过程中,前面回答的问题都比较OK,但是当面试官提出编写一个排序算法的时候,很多面试者脑海中想象排序算法都比较简单,但是当真的让你在编辑器上编程的时候,往往写不出来了,其实排序算法是锻炼编程思维的一种方式,今天我来总结一下使用Python来实现排序算法的相关代码,方便大家阅读和使用。
快速排序代码:
def quick_sort(arr, start, end): if start >= end: return mid = arr[start] left = start right = end while left < right: while arr[right] >= mid and left < right: right -= 1 arr[left] = arr[right] while arr[left] < mid and left < right: left += 1 arr[right] = arr[left] arr[left] = mid quick_sort(arr, start, left - 1) quick_sort(arr, right + 1, end) if __name__ == "__main__": array = [34,56,43,5,7,453,5,6453,265424,35,5475] quick_sort(array, 0, len(array)-1) print(array) ============================================================ 快排结果:[5, 5, 7, 34, 35, 43, 56, 453, 5475, 6453, 265424]
插入排序代码:
def insert_sort(array): for i in range(len(array)): sos = i while array[sos-1] >= array[sos] and sos - 1 >= 0: array[sos], array[sos-1] = array[sos-1], array[sos] sos -= 1 return array if __name__ == "__main__": array = [23,345,56,341,45634,451,567] print(insert_sort(array)) ==================================================== 插入排序算法结果:[23, 56, 341, 345, 451, 567, 45634]
冒泡排序代码:
def buffle_sort(alist): for j in range(len(alist)-1, 0, -1): for i in range(j) if alist[i] > alist[i+1] alist[i], alist[i+1] = alist[i+1], alist[i] if __name__ == "__main__": array = [23,45,546,67,235,76,625,7,34,6,5668,523,6,527] print(buffle_sort(array)) =========================================================================== 冒泡排序算法结果:[6, 6, 7, 23, 34, 45, 67, 76, 235, 523, 527, 546, 625, 5668]
选择排序代码:
def select_sort(arr): for i in range(len(arr)): min_idx = i for j in range(i+1, len(arr)): if arr[min_idx] > arr[j]: min_idx = j arr[i], arr[min_idx] = arr[min_idx], arr[i] if __name__ == "__main__": array = [23,45,546,67,53,562,6,67,55,7] select_sort(array) print(array) ===================================================== 选择排序算法结果:[6, 7, 23, 45, 53, 55, 67, 67, 546, 562]
总结: 代码很简单,理解里面的逻辑是很重要的,非常有助于提高编程的底层思维,具体的实现逻辑这里就不再赘述了,希望这四段代码可以帮助到大家。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)