[关闭]
@liuximing 2018-04-10T18:53:00.000000Z 字数 1193 阅读 135

常用排序算法的Python实现

Python


image_1c8kf1r4r1nai1m3iqeu1cqt1os39.png-46.3kB

  1. #/usr/bin/python
  2. # -*- coding: UTF-8 -*-
  3. #
  4. #pip install numpy
  5. #pip install scipy
  6. #pip install matplotlib
  7. import matplotlib.pyplot as plt
  8. import numpy as np
  9. x = np.linspace(1, 100, 10)
  10. y1 = np.power(x, 2)
  11. plt.plot(x, y1, 'r-o', label='n^2')
  12. y2 = np.multiply(x, np.log2(x))
  13. plt.plot(x, y2, 'g-^', label='nlog2n')
  14. y2 = np.multiply(x, np.log(x))
  15. plt.plot(x, y2, 'b-+', label='nlogn')
  16. plt.legend()
  17. plt.xlabel('nums')
  18. plt.ylabel('time')
  19. plt.title('mean time complexity')
  20. plt.show()

冒泡排序

  1. def bubble_sorts(list):
  2. count = len(list)
  3. for i in range(0, count-1):
  4. for j in range(0, count-1-i):
  5. if list[j] > list[j+1]:
  6. list[j], list[j+1] = list[j+1], list[j]
  7. return list

选择排序

  1. def select_sort(list):
  2. count = len(list)
  3. for i in range(0, count - 1):
  4. max = 0
  5. for j in range(0, count - 1 - i):
  6. if list[max] < list[j + 1]:
  7. max = j + 1
  8. list[max], list[count - 1 - i] = list[count - 1 - i], list[max]
  9. return list

插入排序

  1. def insert_sort(list):
  2. count = len(list)
  3. for i in range(1, count):
  4. current = list[i]
  5. pos = i
  6. while pos > 0 and list[pos - 1] > current:
  7. list[pos] = list[pos - 1]
  8. pos = pos - 1
  9. list[pos] = current
  10. return list

希尔排序

  1. def shell_sort(list):
  2. count = len(list)
  3. step = count / 2
  4. while step > 0:
  5. for i in range(step, count):
  6. current = list[i]
  7. pos = i
  8. while pos > 0 and list[pos - step] > current:
  9. list[pos] = list[pos - step]
  10. pos = pos - step
  11. list[pos] = current
  12. step = step / 2
  13. return list
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注