forked from okoibraun/number-sorter
-
Notifications
You must be signed in to change notification settings - Fork 0
/
number_sorter.py
76 lines (65 loc) · 2.64 KB
/
number_sorter.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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
#!/usr/bin/python
import os
import argparse
from argparse import RawTextHelpFormatter
# Bubble sorting algorithm
def sort_bubble(numbers):
for sorted in reversed(range(len(numbers))):
for index in range(len(numbers[:sorted])):
if numbers[index] > numbers[index + 1]:
numbers[index], numbers[index + 1] = numbers[index + 1], numbers[index]
return numbers
# Insertion sorting algorithm
def sort_insertion(numbers):
for index in range(1, len(numbers)):
for i in reversed(range(index)):
if numbers[index] < numbers[i]:
numbers[index], numbers[i] = numbers[i], numbers[index]
else: break
return numbers
# Selection sorting algorithm
def sort_selection(numbers):
for index in range(len(numbers)):
index_min = index + numbers[index:].index(min(numbers[index:]))
numbers[index], numbers[index_min] = numbers[index_min], numbers[index]
return numbers
# Argument parser
parser = argparse.ArgumentParser()
parser = argparse.ArgumentParser(description='Sort a file containing numbers', formatter_class=RawTextHelpFormatter)
parser.add_argument('file_in',
type=str,
help='file containing unsorted numbers')
parser.add_argument('file_out',
type=str,
nargs='?',
help='file to write sorted number to \n(Default: input file)')
parser.add_argument('-d','--delimiter',
type=str,
default='\n',
help='specify what delimiter to use \n(Default: \"\\n\")')
parser.add_argument('-o','--order',
choices=['ascending','descending'],
default='ascending',
help='specify how numbers should be ordered \n(Default: ascending)')
parser.add_argument('-s','--sorting-algorithm',
choices=['bubble','insertion','selection'],
default='selection',
help='specify what sorting algorithm to use \n(Default: selection)')
args = parser.parse_args()
# Write to input file if no output file is defined
if not args.file_out : args.file_out = args.file_in
def main():
# Read file
numbers = list(map(int, open(args.file_in,'r').read().split(args.delimiter)))
# Sort numbers
{
'bubble' : sort_bubble(numbers),
'insertion' : sort_insertion(numbers),
'selection' : sort_selection(numbers)
}[str(args.sorting_algorithm)]
# Order ascending or descending
if str(args.order) == 'descending' : numbers = reversed(numbers)
# Write file
open(args.file_out, 'w').write(args.delimiter.join(map(str, numbers)))
if __name__ == '__main__':
main()