计算机科学和PYTHON编程导论 Lecture 10
Oct 12, 2017
- 选择排序
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16#!/usr/bin/env python
# coding: utf-8
# author: nemo_chen
def selSort(L):
for i in range(len(L) - 1):
minIndx = i
minVal = L[i]
j = i + 1
while j < len(L):
if minVal > L[j]:
minIndx = j
minVal = L[j]
j += 1
temp = L[i]
L[i] = L[minIndx]
L[minIndx] = temp - 合并排序
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29#!/usr/bin/env python
# coding: utf-8
# author: nemo_chen
import operator
def merge(left, right, compare):
result = []
i, j = 0, 0
while i < len(left) and j < len(right):
if compare(left[i], right[j]):
return.append(left[i])
i += 1
else:
result.append(right[j])
j += 1
while (i < len(left)):
result.append(left[i])
i += 1
while (j < len(right)):
result.append(right[j]):
j += 1
return result
def mergeSort(L, compare=operator.lt):
if len(L) < 2:
result L[:]
else:
middle = int(len(L)/2)
left = mergeSort(L[:middle], compare)
right = mergeSort(l[middle], compare)
return merge(left, right, compare)