-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcw_sort_the_odd.cc
57 lines (47 loc) · 1.4 KB
/
cw_sort_the_odd.cc
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
// Codewars: Sort the odd
// 6 kyu
//
// URL: https://www.codewars.com/kata/578aa45ee9fd15ff4600090d/train/cpp
//
// Task
// You will be given an array of numbers. You have to sort the odd numbers in ascending order
// while leaving the even numbers at their original positions.
//
// Examples
// [7, 1] => [1, 7]
// [5, 8, 6, 3, 4] => [3, 8, 6, 5, 4]
// [9, 8, 7, 6, 5, 4, 3, 2, 1, 0] => [1, 8, 3, 6, 5, 4, 7, 2, 9, 0]
#include <vector>
#include <cassert>
class Kata {
public:
bool is_odd(int num) {
return num % 2 == 1;
}
std::vector<int> sortArray(std::vector<int> array) {
// Edge case.
if (array.size() == 0) return array;
// Iterate through items, bubble sort for odd numbers.
for (int i = 0; (unsigned) i < array.size() - 1; i++) {
if (!is_odd(array[i])) continue;
for (int j = i + 1; (unsigned) j < array.size(); j++) {
if (!is_odd(array[j])) continue;
if(array[i] > array[j]) {
auto temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}
}
return array;
}
};
int main() {
Kata kata;
assert(kata.sortArray(std::vector<int>{ }) == std::vector<int>({ }));
assert(kata.sortArray(std::vector<int>{ 5, 3, 2, 8, 1, 4 }) ==
std::vector<int>({ 1, 3, 2, 8, 5, 4 }));
assert(kata.sortArray(std::vector<int>{ 5, 3, 1, 8, 0 }) ==
std::vector<int>({ 1, 3, 5, 8, 0 }));
return 0;
}