本文给大家分享python四种常见排序方法,每种方法通过实例代码给大家介绍的非常详细,需要的朋友参考下吧
1.冒泡排序
相邻位置比较大小,将比较大的(或小的)交换位置
1 2 3 4 5 6 7 8 9 10 | def maopao(a): for i in range ( 0 , len (a)): for j in range ( 0 , len (a) - i - 1 ): if a[j]>a[j + 1 ]: temp = a[j + 1 ] a[j + 1 ] = a[j] a[j] = temp #print(a) #print(a) print (a) |
2.选择排序
遍历选择一个最小的数与当前循环的第一个数交换
1 2 3 4 5 6 7 8 9 10 11 | def xuanze(a): for i in range ( 0 , len (a)): k = i temp = a[i] for j in range (i, len (a)): if a[j]<temp: temp = a[j] k = j a[k] = a[i] a[i] = temp print (a) |
3.快速排序:
将子段的第一个元素做为中值,先从右向左遍历,如过比中值大high-1,如果比中值小,将这个值放到low那里。
然后从左向右开始遍历,如果左侧的比中值大,将他放到high那里。当low>=high时,将中值的值赋给low
(1.以下为参照公众号中的做法:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | a = [ 7 , 1 , 3 , 2 , 6 , 54 , 4 , 4 , 5 , 8 , 12 , 34 ] def sort(a,low,high): while low < high: temp = a[low] while low < high and a[high]> = temp: high = high - 1 a[low] = a[high] while low<high and a[low]<temp: low = low + 1 a[high] = a[low] a[low] = temp return low def quicksort(a,low,high): if low<high: middle = sort(a,low,high) quicksort(a,low,middle) quicksort(a,middle + 1 ,high) print (a) sort(a, 0 , len (a) - 1 ) quicksort(a, 0 , len (a) - 1 ) print (a) |
(2.以下是参照网上的做法:
在做快速排序时一直各种问题,是因为地柜那里没有考虑清楚,一直把low的值赋值为0了,实际上应该是不固定的low值,他每个子循环不定。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | a = [ 7 , 1 , 3 , 2 , 6 , 54 , 4 , 4 , 5 , 8 , 12 , 34 ] def sort(a,low,high): while low < high: temp = a[low] while low < high and a[high]> = temp: high = high - 1 while low<high and a[high]<temp: a[low] = a[high] low = low + 1 a[high] = a[low] a[low] = temp return low def quicksort(a,low,high): if low<high: middle = sort(a,low,high) quicksort(a,low,middle) quicksort(a,middle + 1 ,high) print (a) sort(a, 0 , len (a) - 1 ) quicksort(a, 0 , len (a) - 1 ) print (a) |
4.插入排序:
从左向右遍历,依次选取数值,从数值的左侧从右向左遍历,选择第一个比他小的数值的右侧插入该数值,其他数值依次向后赋值
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | #插入排序 a = [ 7 , 1 , 3 , 2 , 6 , 54 , 4 , 4 , 5 , 8 , 12 , 34 ] for i in range ( 0 , len (a) - 1 ): temp = a[i + 1 ] j = i + 1 while j> = 0 and temp<a[j - 1 ]: j = j - 1 print (j) if j> = - 1 : k = i + 1 while k> = j: a[k] = a[k - 1 ] k = k - 1 print (a) a[j] = temp print (a) |
插入排序方法2,用到了列表的a.insert(1,2)和清楚a[2:3]=[],这样可以少用一个循环
1 2 3 4 5 6 7 8 9 10 11 12 13 | a = [ 7 , 1 , 3 , 2 , 6 , 54 , 4 , 4 , 5 , 8 , 12 , 34 ] for i in range ( 1 , len (a) - 1 ): temp = a[i] j = i - 1 while j> = 0 and temp< = a[j]: print (temp) j = j - 1 if j > = - 1 : a[i:i + 1 ] = [] a.insert(j + 1 ,temp) print (a) print (a) |
到此这篇关于Python实现排序的四种方法的文章就介绍到这了,希望对你有帮助。
来源:https://www.weidianyuedu.com