@zqbinggong
2018-03-06T21:36:37.000000Z
字数 1505
阅读 953
插入排序
分治模式
归并排序
算法导论
1.Insertion Sort(A) -----
for j = 2 to A.length
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
2.Merge Sort(A,p,r) ------
if p < r
q = (p+r)/2 #向下取整
Merge Sort(A,p,q)
Merge Sort(A,q+1,r)
Merge(A,p,q,r)
Merge(A,p,q,r) -----
n1 = q-p+1
n2 = r-q
let L[1...n1+1] and R[1...n2+1] be bew arrays
for i = 1 to n1
L[i] = A[p+i-1]
for j = 1 to n2
R[j] = A[q+j]
L[n1+1] = R[n2+1] = 00 #setinel cards
i = j = 1
for k = p to r
if L[i] <= R[j]
A[k] = L[i]
i += 1
else
A[k] = R[j]
j += 1
3.其他,
选择排序,冒泡排序,逆序对
3.1Selection Sort(A) -----
n = A.length
for i = 1 to n
smallest = i
for j = i+1 to n
if A[j] <= A[smallest]
smallest = j
exchange A[i] with A[smallest]
3.2 Bubble Sort(A) -----
n = A.length
for i = 1 to n-1
for j = n downto i+1
if A[j] < A[j-1]
exchange A[j] with A[j-1]
3.3 Count Inversions ------
inversions = 0
if p < r
q = (p+r)/2 #向下取整
inversions = inversions + Count Inversions(A,p,q)
inversions = inversions + Count Inversions(A,q+1,r)
inversions = inversions + Merge Inversions(A,p,q,r)
Merge Inversions(A,p,q,r) -----
n1 = q-p+1
n2 = r-q
let L[1...n1+1] and R[1...n2+1] be bew arrays
for i = 1 to n1
L[i] = A[p+i-1]
for j = 1 to n2
R[j] = A[q+j]
L[n1+1] = R[n2+1] = 00 #setinel cards
i = j = 1
inversion = 0
for k = p to r
if L[i] > R[j]
inversions = inversions + n1-i+1
A[k] = R[j]
j += 1
else
A[k] = L[i]
i += 1
return inversion