python 实现快速排序和插入排序

def quick_sort(data):
    if len(data)<2 or (len(data)==2 and data[0]<=data[1]): #[2,3]此情况会死循环 所以加上特例验证
        return data
    mid = data[len(data)//2]
    left,right=[],[]
    #data.remove(mid) #不更改原对象为妙 
    for num in data:
        if num>mid:
            right.append(num)
        if num<=mid:
            left.append(num)
    return quick_sort(left)+quick_sort(right)  #拼接list

def insert_sort(data):
    for i in range(len(data)):
        for j in range(i):
            if data[i]<data[j]:
                data.insert(j,data.pop(i))
                break
    return data
array = [4,2,2,3,1,5,6,7]
arr2 = quick_sort(array)
print(arr2,len(arr2))
print(array,len(array))

arr3 = insert_sort(array)
print(arr3,len(arr3))
print(array,len(array))

list.remove(value) 只是删除first ocurrency of value

d = [3,4,3,5,1]
d.remove(d[2])
print(d)  #[4, 3, 5, 1] #删的不是第二个3

python中变量按照不可变量理解,d[0] is d[2] ==》Ture, 其实是同一对象

posted on 2019-03-16 19:45  ShawSpring  阅读(227)  评论(0编辑  收藏  举报

导航