python代码实现经典排序算法

  排序算法在程序中有至关重要的作用, 不同算法的时间复杂度和空间复杂度都有所区别, 这影响着程序运行的效率和资源占用的情况, 经常对一些算法多加练习, 强化吸收, 可以提高对算法的理解, 进而运用到实践中, 以下是常用的一些算法排序思维, 将以最简单的代码块呈现 :

冒泡排序

1 numbers = [58,35,78,12,6,19,-15,167]
2 #从小到大
3 for i in range(len(numbers)-1):#需要比较几轮
4      for j in range(len(numbers)-1-i):  #内部数据比几次
5         if  numbers[j]  >  numbers[j+1]:
6              #交换位置
7              numbers[j],numbers[j+1] = numbers[j+1],numbers[j]
8  print(numbers)

选择排序

1 numbers = [58,35,78,12,6,19,-15,167]
2 for i in range(len(numbers)-1):   #要取多少次
3     index = i
4     for j in range(i+1,len(numbers)):
5         if numbers[j] < numbers[index]:
6             index = j
7     numbers[i],numbers[index]= numbers[index],numbers[i]
8 
9  print(numbers)

插入排序

 1 numbers = [58,35,78,12,6,19,-15,167]
 2 for i in range(1,len(numbers)):
 3     j = i - 1
 4     if numbers[i] <  numbers[j]:
 5         temp = numbers[i]
 6         numbers[i] = numbers[j]
 7 
 8         j = j -1
 9         while j >= 0 and temp < numbers[j]:
10             numbers[j+1] = numbers[j]
11             j = j -1
12         numbers[j+1] = temp
13 print(numbers)

希尔排序

1 numbers = [58,35,78,12,6,19,-15,167]
2 numLen = len(numbers)
3 while numLen > 1:
4     numLen = numLen // 2
5     for i in range(numLen, len(numbers)):
6         for j in range(i % numLen, i, numLen):
7             if numbers[i] < numbers[j]:
8                 numbers[i], numbers[j] = numbers[j], numbers[i]
9 print(numbers)

快速排序

 1 numbers = [58,35,78,12,6,19,-15,167]
 2 def sorting(begin, end):
 3     if begin > end:
 4         return
 5     b, e = begin, end
 6     pivot = numbers[b]
 7     while b < e:
 8         while b < e and numbers[e] > pivot:
 9             e -= 1
10         while b < e and numbers[b] <= pivot:
11             b += 1
12         numbers[b], numbers[e] = numbers[e], numbers[b]
13     numbers[b], numbers[begin] = pivot, numbers[b]
14     sorting(begin, b - 1)
15     sorting(e + 1, end)
16 sorting(0, len(numbers) - 1)
17 print(numbers)

 


技术交流可以留言评论哦 ! 虚心学习, 不忘初心, 共同奋进 !

posted @ 2018-07-05 20:17  西雅图记  阅读(238)  评论(0编辑  收藏  举报