码迷,mamicode.com
首页 > 编程语言 > 详细

选择排序

时间:2018-07-21 12:18:15      阅读:141      评论:0      收藏:0      [点我收藏+]

标签:div   print   操作   sorted   pop   pen   sub   排序   find   

## 选择排序需要执行n次时间为O(n)的操作,所以总时间为O(n2)

 

 1 def find_smallest(arr):
 2     """return the index of the smallest element"""
 3     smallest = arr[0]
 4     smallest_index = 0
 5     for i in range(0, len(arr)):
 6         if arr[i] < smallest:
 7             smallest = arr[i]
 8             smallest_index = i
 9     return smallest_index
10 
11 def selection_sort(arr):
12     sorted_arr = []
13     for i in range(0, len(arr)):
14         smallest_index = find_smallest(arr)
15         sorted_arr.append(arr.pop(smallest_index))
16     return sorted_arr
17 
18 print(selection_sort([2,3,4,5,7,2,21,-2,-4,-9]))
19 # [-9, -4, -2, 2, 2, 3, 4, 5, 7, 21]

 

选择排序

标签:div   print   操作   sorted   pop   pen   sub   排序   find   

原文地址:https://www.cnblogs.com/hycstar/p/9345491.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!