基本排序演算法,包括氣泡排序,插入排序,選擇排序,堆排序,快速排序等。
【氣泡排序】
複雜度是n*n
#coding:utf8【插入排序】#author:haxtraz
#description:氣泡排序
def bubblesort1(a):
#每次找到乙個最小元素,放到陣列首部
n=len(a)
for i in range(0,n-1):
for j in range(n-1,i,-1):
if a[j]a[j+1]:
a[j],a[j+1]=a[j+1],a[j]
def bubblesort3(a):
#這個版本來自維基百科
#外層迴圈本來有點問題的,如果是range(len(a)-1,1,-1)
#那麼當輸入資料為3,5,1時,結果不正確
#當然,維基百科上這個錯誤我已經修改過了。
for j in range(len(a)-1, 0, -1):
for i in range(0, j):
if a[i]>a[i+1]:
a[i],a[i+1]=a[i+1],a[i]
複雜度是n*n
#coding:utf8【選擇排序】#author:haxtraz
def insertion_sort1(a):
#線性插入排序
for j in range(1, len(a)):
key = a[j]
i = j - 1
while i>=0 and a[i]>key:
a[i+1] = a[i]
i = i-1
a[i+1] = key
def bininsertsort(a):
#二分插入排序
n = len(a)
for j in range(1, n):
key = a[j]
i = j - 1
if key > a[i]:
continue
l, r = 0, i
while l <= r:
#print l, r
mid = (l + r) / 2
if key < a[mid]:
r = mid - 1
else:
l = mid + 1
k = j
while k > l:
a[k] = a[k - 1]
k = k - 1
a[l] = key
複雜度是n*n
#coding:utf8【堆排序】#author:haxtraz
#description:選擇排序
def selectsort1(a):
#每次找最小元素
n=len(a)
for i in range(0, n-1):
for j in range(i+1, n):
minpos=i #minpos用於記錄最小元素的下標
if a[j]a[maxpos]:
maxpos=j
if maxpos!=i:
a[i],a[maxpos]=a[maxpos],a[i]
複雜度是nlogn
#coding:utf8【快速排序】#author:haxtraz
#description:堆排序
#修改自《演算法導論》2nd edition
def left(i):
return 2*i+1
def right(i):
return 2*i+2
def parent(i):
return (i-1)/2
def max_heapify(a,i,heapsize):
l=left(i)
r=right(i)
if la[i]:
largest=l
else:
largest=i
if ra[largest]:
largest=r
if largest!=i:
a[i],a[largest]=a[largest],a[i]
max_heapify(a,largest,heapsize)
def build_max_heap(a):
heapsize=len(a)
i=parent(len(a)-1)
while i>=0:
max_heapify(a,i,heapsize)
i -= 1
def heap_sort(a):
build_max_heap(a)
n=len(a)
heapsize=n
for i in range(n-1, 0, -1):
a[0],a[i]=a[i],a[0]
heapsize-=1
max_heapify(a,0,heapsize)
a=[1,3,2,4,8,6,22,9]
heap_sort(a)
print a
複雜度是nlogn
#coding:utf8#version1
'''參考自'''
def quicksort(alist):
quicksorthelper(alist,0,len(alist)-1)
def quicksorthelper(alist,first,last):
if first= pivotvalue and \
rightmark >= leftmark:
rightmark = rightmark -1
if rightmark < leftmark:
done = true
else:
temp = alist[leftmark]
alist[leftmark] = alist[rightmark]
alist[rightmark] = temp
temp = alist[first]
alist[first] = alist[rightmark]
alist[rightmark] = temp
return rightmark
alist = [54,26,93,17,77,31,44,55,20]
quicksort(alist)
print(alist)
基本排序演算法 Python實現
基本排序演算法,包括氣泡排序,插入排序,選擇排序,堆排序,快速排序等。氣泡排序 複雜度是n n coding utf8 author haxtraz description 氣泡排序 def bubblesort1 a 每次找到乙個最小元素,放到陣列首部 n len a for i in range...
python實現基本演算法
classnode object 建立節點類 def init self elem 1 lchild none,rchild none self.elem elem self.lchild lchild self.rchild rchild 就是每次將樹中的節點依次取出來,放入佇列,判斷 class...
Java實現基本排序演算法
public class sort public static sort getinstance return sort private void move int array,int from,int end 交換陣列中的兩個元素的位置 param array 待交換的陣列 param i 第乙個...