Python排序算法

1、插入排序

def insertinto_sort(arr):
  for k in range(1, len(arr)):
    cur = arr[k]
    j = k
    while j > 0 and arr[j-1] > cur:
      arr[j] = arr[j-1]
      j -= 1
    arr[j] = cur
  return arr

2、选择排序

def select_sort(arr):
  for i in range(1, len(arr)):
    min_index = i
    for j in range(i+1,len(arr)):
      if arr[j] < arr[min_index]:
        min_index = j
    if i != min_index:
      arr[i],arr[min_index] = arr[min_index],arr[i]
  return arr

3、快速排序

def quick_sort(arr):
  if len(arr) < 2: 
    return arr
  q = arr[0]
  L = []
  E = []
  R = []
  while arr:
    cur = arr.pop(0)
    if cur < q:
      L.append(cur)
    elif cur > q:
      R.append(cur)
    else:
      E.append(cur)
  quick_sort(L)
  quick_sort(R)
  while L:
    arr.append(L.pop(0))
  while E:
    arr.append(E.pop(0))
  while R:
    arr.append(R.pop(0))
  return arr

posted @ 2021-05-30 10:31  LZ站长  阅读(48)  评论(0)    收藏  举报