-
Notifications
You must be signed in to change notification settings - Fork 0
/
selection_sort.py
52 lines (43 loc) · 1.32 KB
/
selection_sort.py
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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
import sys
import time
def selection_sort(l):
s = []
while l != []:
x = l[0]
for y in l:
if y < x:
x = y
l.remove(x)
s.append(x)
return s
def print_ten_words(l):
print('first 10 words: ', end='')
for i in range(10):
print('[{}]'.format(l[i]), end='')
def main():
if len(sys.argv) != 3:
print('Error, must supply 2 arguments.\n\n' +
'Usage: python3 project_3.py <text_file> <n>')
sys.exit(1)
filename = sys.argv[1]
n = int(sys.argv[2])
# read up to n words from the file
word_list = []
input_file = open(filename, 'r')
for i in range(n):
word_list.append(input_file.readline().rstrip())
input_file.close()
# print input information and first 10 words of input list
print('requested n = {}'.format(n))
print("loaded {} lines from '{}'".format(n, filename))
print_ten_words(word_list)
print('\nselection sort...')
# run and time the selection sort algorithm
start = time.perf_counter()
sorted_list = selection_sort(word_list)
end = time.perf_counter()
# print run time information and first 10 words of sorted list
print_ten_words(sorted_list)
print('\nelapsed time: {} seconds'.format(end - start))
if __name__ == '__main__':
main()