# -*- coding: utf-8 -*-
"""
Created on Sat Aug 3 15:49:38 2019
function:快速排序
@author: Administrator
"""
#import numpy as np
import random
def MergeSort(array):
if(len(array)<2):
return array
else:
mid=int(len(array)/2)
left=array[0:mid]
right=array[mid:len(array)]
return merge(MergeSort(left),MergeSort(right))
def merge(left,right):
result=[0]*(len(left)+len(right))
print('left的长度')
print(len(left))
print('right的长度')
print(len(right))
print('result的长度')
print(len(result))
print('result')
print(result)
i=0
j=0
for index in range(len(result)):
if i>=len(left):
result[index]=right[j]
j+=1
elif j>=len(right):
result[index]=left[i]
i+=1
elif left[i]>right[j]:
result[index]=right[j]
j+=1
else:
result[index]=left[i]
i+=1
return result
def quick_sort(array,l,r):
if l<r:
q=partition(array,l,r)
quick_sort(array,l,q-1)
quick_sort(array,q+1,r)
def partition(array,l,r):
x=array[r]
q=l-1
# pvoit=l+random.randint(0,(r-l+1))
# array[pvoit],array[r]=array[r],array[pvoit]
for i in range(l,r):
if(array[i]<=x):
q+=1
array[i],array[q]=array[q],array[i]
array[q+1],array[r]=array[r],array[q+1]#最后一定要把这个数放到该放的位置
return q+1
if __name__=='__main__':
print("排序前的数组为")
a=[0]*40
for i in range(40):
a[i]=100*random.random()
print(a[i])
quick_sort(a,0,len(a)-1)
print("采用快速排序法之后的数组:")
for i in range(40):
print(a[i])
print("排序前的数组为")
a=[0]*40
for i in range(40):
a[i]=100*random.random()
print(a[i])
b=MergeSort(a)
print("采用归并排序法之后的数组:")
for i in range(len(b)):
print(b[i])