All sorts of sorts...deadly! ! Code it every day! ! !

Not finished yet……………………
Insert picture description here

Insertion sort

For sorting a small number of elements, this is an effective algorithm
Insert picture description here
Insert picture description here

# 插入排序
def insert_sort(list):
  # 从第二个元素开始,依次加入有序队列中
  for i in range(1,len(list)):
    # 将list[i]插入已经排序好的队列list[0,...,i-1]中
    if list[i] < list[i-1]:
      key = list[i]
      index = i
      # 从后往前依次比较每个元素
      for j in range(i-1,-1,-1):
        if list[j] > key:
          list[j+1] = list[j]
          index = j
        else:
          break
      list[index] = key
  return list

# 底下这个感觉更好理解一些
def insert_sort(list):
  # 从第二个元素开始,依次加入有序队列中
  for j in range(1,len(list)):
    key = list[j]
    i = j - 1
    while i>0 and list[i] > key:
      list[i+1] = list[i]
      i = i - 1
    list[i+1] = key
  return list

shell sorting

Shell sorting is also a kind of insertion sorting. It is a more efficient version of simple insertion sorting after improvements. It has also become a reduced incremental sorting. In
将较大的数据集分割成若干个小组,然后对每个小组分别进行插入排序。
each gap process, each group is ordered internally.
Insert picture description here

def shell_sort(list):
  gap = len(list)//2
  while gap>0:
    for i in range(gap,len(list)):
      for j in range(i,gap-1,-gap):
        if list[j]<list[j-gap]:
          list[j],list[j-gap] = list[j-gap],list[j]
        else:
          break
    gap = gap // 2
  return list

Select sort

  1. First find the minimum element among all array elements and place it in list[0];
  2. Then find the element with the smallest value among the remaining array elements that do not contain list[0] and place it in list[1];
  3. And so on, until the last element.

Insert picture description here

def select_sort(list):
  for i in range(len(list)):
    min = i
    for j in range(i+1,len(list)):
      if list[j] < list[min]:
        min = j
    tmp = list[i]
    list[i] = list[min]
    list[min] = tmp
  return list

Heap sort

Insert picture description here
Insert picture description here
Insert picture description here

Bubble Sort

One round of one round of processing.
In each round, the two adjacent elements in the sorted array elements are compared in turn, and the big one is placed in the front, and the small is placed in the back-descending order (or the small is placed in the front, After the big ones are put in ascending order)
When there is no exchange, the data has been sorted
Insert picture description here

# 升序排序
# 每一轮次把当前最大的冒到最后
def bubble_sort(list):
  for i in range(len(list)):
    for j in range(1,len(list)-i):
      if list[j] < list[j-1]:
        tmp = list[j-1]
        list[j-1] = list[j]
        list[j] = tmp
  return list

Quick sort

Merge sort

Insert picture description here
Insert picture description here
Insert picture description here

Base sort

Guess you like

Origin blog.csdn.net/weixin_39333120/article/details/111561269