/*
第一次写py代码,写个小算法以熟悉py的基本语法。
QuickSort.py
*/
def Test1():
print ("begin !")
list = [10,9,8,7,6,5,4,3,2,1]
QuickSort(list,0,9)
for l in list:
print (str(l))
return
def QuickSort(sortList,beginIndex,endIndex):
PrintList(sortList,beginIndex,endIndex)
if( endIndex-beginIndex + 1 == 2): #刚好要排序的只有两个
ExchangeElementInList(sortList,beginIndex,endIndex)
elif(endIndex-beginIndex + 1 <= 1):
DoNothing()
else:
result = HandleList(sortList,beginIndex,endIndex)
QuickSort(sortList,result[0],result[1])
QuickSort(sortList,result[2],result[3])
return
def DoNothing():
return
def ExchangeElementInList(list,elIndex1,elIndex2):
if list[elIndex2] >= list[elIndex1] :
return
else :
temp = list[elIndex1]
list[elIndex1] = list[elIndex2]
list[elIndex2] = temp
return
def HandleList(list,elIndex1,elIndex2):
newList1 = []
newList2 = []
result = [] #0:left begin 1:left end 2:right begin 3:right end
baseNum = list[elIndex1]
for index in range(elIndex2-elIndex1):
id = index+elIndex1+1
if list[id] >= baseNum :
newList2.append(list[id])
else :
newList1.append(list[id])
index = elIndex1
for id in range(len(newList1)):
list[index] = newList1[id]
index = index+1
result.append(elIndex1)
result.append(index-1)
list[index] = baseNum
index=index+1
result.append(index)
result.append(elIndex2)
for id in range(len(newList2)):
list[index] = newList2[id]
index = index+1
return result
def PrintList(list,startIndex,endIndex):
return
index = startIndex
print("------- print array from "+str(startIndex)+" to "+str(endIndex)+" -------")
while index<= endIndex :
print(list[index])
index = index+1
print("------- end -------------")
#run
Test1()