8000 Added BitSort with bitarray C extension. · pythonpeixun/practice-python@170312d · GitHub
[go: up one dir, main page]

Skip to content

Commit 170312d

Browse files
committed
Added BitSort with bitarray C extension.
1 parent eadca96 commit 170312d

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed

interview/sorting_linear_optimized.py

Copy file name to clipboard
Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
"""
2+
Task:
3+
4+
Implement an algorithm to sort 1,000,000 32-bit integers, using only 350K of memory.
5+
The numbers could be any number from 0 to 9,999,999
6+
The numbers are in a file, one line per number. There are no duplicates.
7+
Output the numbers, one to a line, to a file.
8+
The algorithm must be linear-time.
9+
"""
10+
11+
import bitarray
12+
13+
14+
class Bitsort(object):
15+
16+
def __init__(self, max_number):
17+
self._int_bits = 32
18+
self._bit_array = bitarray.bitarray([False] * (max_number + 1)) # 1 for 0
19+
20+
def save_number(self, number):
21+
self._bit_array[number] = True
22+
23+
def get_sorted_numbers(self):
24+
for index, bit in enumerate(self._bit_array):
25+
if bit is True:
26+
yield index
27+
28+
29+
def main():
30+
bitsorter = Bitsort(9999999)
31+
32+
with open("numbers.txt", "r") as in_file:
33+
for line in in_file:
34+
bitsorter.save_number(int(line.rstrip()))
35+
36+
out_file = open("out.txt", "w", 4096)
37+
for number in bitsorter.get_sorted_numbers():
38+
out_file.write(str(number) + "\n")
39+
40+
41+
if __name__ == "__main__":
42+
main()

0 commit comments

Comments
 (0)
0