python 各类排序方法
程序员文章站
2024-03-17 22:17:52
...
# _*_ encoding:utf-8 *_*
class Solution:
def insertsort(self, num_list):
"""
插入排序
"""
length = len(num_list)
for i in range(1, length):
tmp = num_list[i]
j = i
while j > 0 and tmp < num_list[j-1]:
num_list[j] = num_list[j-1]
j -= 1
num_list[j] = tmp
def bubblesort(self, num_list):
"""
冒泡排序
"""
length = len(num_list)
for i in range(length-1):
for j in range(length-i-1):
if num_list[j] > num_list[j+1]:
num_list[j], num_list[j+1] = num_list[j+1], num_list[j]
def mergesort(self, num_list):
"""
归并排序
"""
if len(num_list) == 1:
return num_list
half = len(num_list)/2
left = self.mergesort(num_list[:half])
right = self.mergesort(num_list[half:])
return self.merge(left, right)
def merge(self, left, right):
result = []
l, r = 0, 0
while l < len(left) and r < len(right):
if left[l] < right[r]:
result.append(left[l])
l += 1
else:
result.append(right[r])
r += 1
result += left[l:]
result += right[r:]
return result
def quicksort(self, num_list, start, end):
# 快速排序
if end-start < 1:
return
index = self.partion(num_list, start, end)
self.quicksort(num_list, start, index-1)
self.quicksort(num_list, index+1, end)
def partion(self, num_list, start, end):
import random
index = random.randint(start, end)
num_list[index], num_list[end] = num_list[end], num_list[index]
small = start - 1
for index in range(start, end):
if num_list[index] < num_list[end]:
small += 1
if small != index:
num_list[small], num_list[index] = num_list[index], num_list[small]
small += 1
num_list[small], num_list[end] = num_list[end], num_list[small]
return small