-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinsertion_sort
More file actions
63 lines (56 loc) · 1.44 KB
/
insertion_sort
File metadata and controls
63 lines (56 loc) · 1.44 KB
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
#include <iostream>
#include <utility>
#include <sstream>
using namespace std;
void insertion_sort(double * array, unsigned int size) {
unsigned int i, j;
for (i = 1; i < size; i++) {
j = i;
while (j > 0 && array[j] < array[j - 1]) {
swap (array[j], array[j - 1]);
j = j - 1;
}
}
/* Либо через for:
for (i = 1; i < size; i++) {
for (j = i; j > 0 && array[j] < array[j - 1]; j--) {
swap (array[j], array[j - 1]);
}
} */
}
bool read (istream & stream, double* &array, unsigned int &size) {
bool res = true;
for (unsigned int i=0; i < size; i++) {
if (!(stream >> array[i])) {
res = false;
break;
}
}
return res;
}
void write(ostream & stream,double* array, unsigned int size) {
for (unsigned int i = 0; i < size; i++) {
stream << array[i] << ' ';
}
}
int main() {
unsigned int size;
double* array;
if(!(cin >> size)) {
cout << "An error has occured while reading numbers from line";
return 1;
}
cin.get();
string string;
getline(cin, string);
istringstream stream(string);
array = new double [size];
if( read(stream,array, size)) {
insertion_sort (array, size);
write (cout, array, size);
}
else {
cout << "An error has occured while reading numbers from line";
}
delete[] array;
}