Python 的5个基本排序算法
下面是我自己写的一个Python类,主要用到的技术:
- 基本的排序算法
- 利用Python的operator实现了switch的功能。
- 非递归实现:快速排序算法
#!/usr/bin/env python
# -*- coding:utf-8 -*-
from __future__ import division
'this is nums sort class'
__author__='yinao'
class Sort():
def __quickPartition(self,l,low,high):
key=l[low]
while low<high:
while low<high and key<=l[high]:
high=high-1
l[low]=l[high]
while low<high and key>=l[low]:
low=low+1
l[high]=l[low]
l[low]=key
return low
def __quickSort(self,l):
lowList=[]
highList=[]
lowList.append(0)
highList.append(len(l)-1)
while len(lowList)>0 and len(highList)>0:
low=lowList[len(lowList)-1]
lowList.pop()
high=highList[len(highList)-1]
highList.pop()
partition=self.__quickPartition(l,low,high)
if partition+1<high:
lowList.append(partition+1)
highList.append(high)
if partition-1>low:
lowList.append(low)
highList.append(partition-1)
#print(partition)
print(l)
print('quick sorting is over')
#print('this is quickSort')
def __insertSort(self,l):
listLength=len(l)
for i in range(1,listLength):
if l[i-1]>l[i]:
key=l[i]
j=i;
while j>0 and key<l[j-1]:
l[j]=l[j-1]
j=j-1
l[j]=key
print(l)
print('insert sorting is over')
#print('this is insertSort')
def __selectSort(self,l):
listLength=len(l)
for i in range(0,listLength-1):
for j in range(i+1,listLength):
if l[i]>l[j]:
temp=l[i]
l[i]=l[j]
l[j]=temp
print(l)
print('select sorting is over')
#print('this is selectSort')
def __stackAdjust(self,l,start,length):
tmp=l[start]
child=start*2+1
while child<length:
if child+1<length and l[child]<l[child+1]:
child=child+1
if l[start]<l[child]:
l[start]=l[child]
start=child
child=2*start+1
else:
break
l[start]=tmp
pass
def __buildStack(self,l,length):
start=(length-1)//2
while start>=0:
self.__stackAdjust(l,start,length)
start=start-1
pass
def __stackSort(self,l):
length=len(l)
self.__buildStack(l,length)
start=length-1
while start>0:
temp=l[start]
l[start]=l[0]
l[0]=temp
self.__stackAdjust(l,0,start)
start=start-1
print(l)
print('stack sorting is over')
#print('this is stackSort')
def __bubbleSort(self,l):
listLength=len(l)
for i in range(0,listLength-1):
for j in range(i+1,listLength):
if l[i]>l[j]:
temp=l[i]
l[i]=l[j]
l[j]=temp
print(l)
print('bubble sorting is over')
#print('this is bubbleSort')
operator = {
'quick': __quickSort,
'insert': __insertSort,
'select':__selectSort,
'stack':__stackSort,
'bubble':__bubbleSort
}
def run(self,method,l):
#self.operator.get(method)(l)
if self.operator.get(method)==None:
print('please input right method!!!!!!!!!!!!!!!!!!!!!!!!!!!!!')
else:
self.operator.get(method)(self,l)
if __name__=='__main__':
sort=Sort()
method=input('please input methods:')
while True and method!='#':
sort.run(method,[34,23,12,533,2,3,2,12,3233])
method=input('please input methods:')