1: #insert sort
2: def InsertSort(a):
3: for i in range(1,len(a)):
4: tmp = a[i]
5: k = i
6: j=i-1
7: while j >= 0 and a[j] > tmp :
8: a[j+1] = a[j]
9: k = j
10: j = j- 1
11: a[k] = tmp
12:
13: #select sort
14: def SelectSort(a):
15: for i in range(0,len(a)):
16: min = a[i]
17: k = i
18: for j in range(i+1,len(a)):
19: if min > a[j] :
20: min = a[j]
21: k = j
22:
23: a[k] = a[i]
24: a[i] = min
25:
26: #bubble sort
27: def BubbleSort(a):
28: for i in range(len(a)-1,-1,-1):
29: for j in range(0,i):
30: if a[j] > a[j+1] :
31: a[j+1],a[j] = a[j],a[j+1]
32:
33: #merge sort
34: def MergeSort(a):
35: _mergeSort(a,0,len(a)-1)
36:
37: def _mergeSort(a,l,r):
38: length = r - l + 1
39: if length == 1 :
40: pass
41: elif length == 2 :
42: if a[l] > a[r] :
43: a[l],a[r] = a[r],a[l]
44: else :
45: m = l + length / 2
46: _mergeSort(a,l,m)
47: _mergeSort(a,m+1,r)
48: merge(a,l,m,r)
49: #merge
50: def merge(a,i,j,k):
51: m = i
52: n = j + 1
53: b = []
54: while m <= j and n <= k :
55: if a[m] < a[n] :
56: b.append(a[m])
57: m = m + 1
58: elif a[n] < a[m] :
59: b.append(a[n])
60: n = n + 1
61: if m <= j :
62: b = b + a[m:j+1]
63: if n <= k :
64: b = b + a[n:k+1]
65: n = n + 1
66: a[i:k+1] = b[0:len(b)]
67:
68: #heap sort
69: def HeapSort(a) :
70: heapify(a)
71: a[0],a[len(a)-1] = a[len(a)-1],a[0]
72: for n in range(len(a)-1,0,-1):
73: sink(a,1,n)
74: a[0],a[n-1] = a[n-1],a[0]
75:
76: #adjust a heap from the ith node
77: def sink(a,i,n):
78: l = 2 * i
79: r = l + 1
80: if l>n :
81: pass
82: elif l == n :
83: if a[i-1] < a[l-1] :
84: a[i-1],a[l-1] = a[l-1],a[i-1]
85: elif r <= n :
86: pos = l
87: if a[l-1] < a[r-1] :
88: pos = r
89: if a[i-1] < a[pos-1] :
90: a[i-1],a[pos-1] = a[pos-1],a[i-1]
91: sink(a,pos,n)
92: #make a heap
93: def heapify(a):
94: for i in range(len(a)/2,0,-1):
95: sink(a,i,len(a))
96:
97: #quick sort
98: def QuickSort(a):
99: _quickSort(a,0,len(a)-1)
100:
101: def _quickSort(a,l,r):
102: if l >= r:
103: return
104: index = partation(a,l,r)
105: _quickSort(a,l,index-1)
106: _quickSort(a,index+1,r)
107:
108: #partation
109: def partation(a,l,r):
110: key = a[r]
111: i = l - 1
112: j = l
113: for j in range(l,r):
114: if a[j] <= key :
115: i = i + 1
116: a[i],a[j] = a[j],a[i]
117: a[i+1],a[r] = a[r],a[i+1]
118: return i + 1