diff options
| author | Andrew Guschin <guschin.drew@gmail.com> | 2022-04-27 14:04:40 +0400 |
|---|---|---|
| committer | Andrew Guschin <guschin.drew@gmail.com> | 2022-04-27 14:04:40 +0400 |
| commit | 9b53b8e935a648e225508e51f45d83dfaeacd896 (patch) | |
| tree | 3d10c862f19d04814cc9a63abef91cfa707c3ce1 | |
| parent | ca510e0f9f3da8560ac72a4c80b33b167582e5e5 (diff) | |
Переписал сортировку прямым выбором на c++
| -rw-r--r-- | straight-selection.c | 44 | ||||
| -rw-r--r-- | straight-selection.cpp | 47 |
2 files changed, 47 insertions, 44 deletions
diff --git a/straight-selection.c b/straight-selection.c deleted file mode 100644 index f05d098..0000000 --- a/straight-selection.c +++ /dev/null @@ -1,44 +0,0 @@ -#include <stdio.h> - -void -straight_selection(int *array, size_t size) -{ - for (int i = 0; i < size; ++i) - { - int k = i; - int x = array[i]; - for (int j = i; j < size; ++j) - { - if (array[j] < x) - { - k = j; - x = array[j]; - } - } - array[k] = array[i]; - array[i] = x; - } -} - -void -print_array(int *array, size_t size) -{ - if (size == 0) printf("array = { }\n"); - - printf("array = { "); - for (int i = 0; i < size - 1; ++i) - printf("%i, ", array[i]); - printf("%i };\n", array[size - 1]); -} - -int -main() -{ - int array[] = { 2, 7, 12, 30, 11, 4, 12, 5, 20 }; - size_t size = sizeof(array) / sizeof(*array); - print_array(array, size); - straight_selection(array, size); - print_array(array, size); - - return 0; -} diff --git a/straight-selection.cpp b/straight-selection.cpp new file mode 100644 index 0000000..ff5a7b6 --- /dev/null +++ b/straight-selection.cpp @@ -0,0 +1,47 @@ +#include <iostream> +#include <vector> +#include <ostream> + +template<class T> void +straight_selection(std::vector<T> &array) +{ + for (int i = 0; i < array.size(); ++i) + { + int k = i; + int x = array[i]; + for (int j = i; j < array.size(); ++j) + { + if (array[j] < x) + { + k = j; + x = array[j]; + } + } + array[k] = array[i]; + array[i] = x; + } +} + +template<class T> std::ostream & +operator<<(std::ostream &stream, std::vector<T> &v) +{ + if (v.size() == 0) stream << "{ }"; + + stream << "array = { "; + for (int i = 0; i < int(v.size()) - 1; ++i) + stream << v[i] << ", "; + + stream << v.back() << " }"; + return stream; +} + +int +main() +{ + std::vector<int> array = { 2, 7, 12, 30, 11, 4, 12, 5, 20 }; + std::cout << array << std::endl; + straight_selection(array); + std::cout << array << std::endl; + + return 0; +} |