-
Notifications
You must be signed in to change notification settings - Fork 0
/
sort.cpp
96 lines (77 loc) · 2.33 KB
/
sort.cpp
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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
#include <vector>
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <ctime>
#include <cstring>
void printUsage(char* name) {
std::cout << "usage: " << name << " -f input_file" << std::endl;
}
std::vector<int> readFromFile(char* filename) {
std::vector<int> values = std::vector<int>();
/* Open input file */
std::ifstream in(filename);
/* Read all integers from file */
if(in) {
int v;
while(in >> v) {
values.push_back(v);
}
}
in.close();
return values;
}
void writeToFile(char* filename, std::vector<int> &values) {
/* Open output file */
std::ofstream out;
out.open(filename, std::ofstream::out);
/* Write all integers to file */
for(int v : values) {
out << v << "\n";
}
out.close();
}
void swap(std::vector<int> &values, int firstIndex, int secondIndex) {
int tmp = values[firstIndex];
values[firstIndex] = values[secondIndex];
values[secondIndex] = tmp;
}
void sortHelper(std::vector<int> &values, int start, int end) {
/* Check if already sorted */
if(end - start <= 1) return;
/* Pick the first element as the pivot,
we already know the elements are random
so this is as good as a random pivot */
int pivot = values[start];
int swapIndex = start + 1;
for(int index = start + 1; index < end; index++) {
/* Move elements smaller than pivot value to the front
of the list */
if(values[index] < pivot) {
swap(values, index, swapIndex);
swapIndex++;
}
}
/* Swap pivot to appropriate point in list,
since elements to the left of the pivot are smaller,
and the pivot is at the zeroth position,
it should swap with a smaller value, i.e. swapIndex - 1 */
swap(values, start, swapIndex - 1);
/* Sort sublists */
sortHelper(values, start, swapIndex);
sortHelper(values, swapIndex, end);
}
void sort(std::vector<int> &values) {
sortHelper(values, 0, values.size());
}
int main(int argc, char *argv[]) {
/* Must provide -f */
if (argc != 3 || strncmp(argv[1], "-f", 3) != 0) {
printUsage(argv[0]);
return 1;
}
std::vector<int> values = readFromFile(argv[2]);
sort(values);
writeToFile(argv[2], values);
return 0;
}