1.6习题
3. 程序如下
#!/usr/bin/env python
# encoding: utf-8
"""
@version: ??
@author: Dawei Gao
@contact: david_gao@buaa.edu.cn
@software: PyCharm
@file: dataForSorting.py
@time: 2017/10/17 下午9:04
"""
import time
from random import *
def dataGen(n):
"""
产生包含 n个 小于10 000 000的 不重复 的 整数 的文件夹
:param n:
:return:
"""
f = open('dataForSorting.txt', 'w')
a = [0] * 10000000
count = 0
while count < n:
m = randint(0,10000000-1)
if a[m] == 0:
f.write(str(m) + "\n")
count += 1
a[m] = 1
f.close()
def bitSort():
a = [0] * 10000000
for line in open('dataForSorting.txt','r'):
a[int(line)] = 1
# output
res = open('res_dataForSorting_bitsort.txt','w')
for i in range(len(a)):
if a[i]==1:
res.write(str(i)+"\n")
res.close()
def sysSort():
# read
a = []
for line in open('dataForSorting.txt', 'r'):
a.append(int(line))
a.sort()
# output
res = open('res_dataForSorting_syssort.txt', 'w')
for m in a:
res.write(str(m) + "\n")
res.close()
if __name__ == '__main__':
# 产生数据
#dataGen(1000000)
# 位图排序
stime = time.clock()
bitSort()
etime = time.clock()
print("bitSort: "+str((etime-stime)) + "s")
# 快排
stime = time.clock()
sysSort()
etime = time.clock()
print("sysSort: " + str((etime - stime)) + "s")
注意这里位图排序方法并未采用真正意识上的“位”,仍是采用数组完成的。因为不清楚python如何直接在内存里写二进制数0/1(即0/1只占一个bit),现在还不清楚如何实现。
输出结果为
bitSort: 2.155071s
sysSort: 1.945613s
Process finished with exit code 0
根据输出结果,在内存足够的情况下(且都采用32位整数的存储方式时),快排的效率是要比位图排序更高的。
4. 程序如下
def dataGen(n, k):
"""
产生包含 k个 小于 n 的 不重复 的 整数 的文件夹
:param n:
:param k:
:return:
"""
f = open('dataForSorting.txt', 'w')
a = [0] * k
count = 0
while count < k:
m = randint(0,n-1)
if a[m] == 0:
f.write(str(m) + "\n")
count += 1
a[m] = 1
f.close()
5.
如果1M的空间是严格的化,即按照位图排序方法也无法创建容纳10 000 000个整数的数组。
方法一:可以先将1M能够容纳的数字统计下来,即
1M=1024∗1024byte