TheAlgorithms/C++
1.0.0
All the algorithms implemented in C++
Toggle main menu visibility
Loading...
Searching...
No Matches
wiggle_sort.cpp
Go to the documentation of this file.
1
19
20
#include <algorithm>
21
#include <cassert>
22
#include <cstdint>
23
#include <ctime>
24
#include <iostream>
25
#include <vector>
26
31
namespace
sorting
{
37
namespace
wiggle_sort
{
38
52
template
<
typename
T>
// this allows to have vectors of ints, double, float,
53
// etc
54
std::vector<T>
wiggleSort
(
const
std::vector<T> &arr) {
55
uint32_t size = arr.size();
56
57
std::vector<T> out(
58
arr);
// create a copy of input vector. this way, the original input
59
// vector does not get modified. a sorted array is is returned.
60
61
for
(
int
i = 0; i < size; i += 2) {
62
if
(i > 0 && out[i - 1] > out[i]) {
63
std::swap(out[i], out[i - 1]);
// swapping the two values
64
}
65
66
if
(i < size - 1 && out[i] < out[i + 1]) {
67
std::swap(out[i], out[i + 1]);
// swapping the two values
68
}
69
}
70
71
return
out;
// returns the sorted vector
72
}
73
}
// namespace wiggle_sort
74
}
// namespace sorting
75
85
template
<
typename
T>
86
static
void
displayElements
(
const
std::vector<T> &arr) {
87
uint32_t size = arr.size();
88
89
std::cout <<
"Sorted elements are as follows: "
;
90
91
std::cout <<
"["
;
92
93
for
(
int
i = 0; i < size; i++) {
94
std::cout << arr[i];
95
if
(i != size - 1) {
96
std::cout <<
", "
;
97
}
98
}
99
100
std::cout <<
"]"
<< std::endl;
101
}
102
107
static
void
test
() {
108
std::srand(std::time(
nullptr
));
// initialize random number generator
109
110
std::vector<float> data1(100);
111
for
(
auto
&d : data1) {
// generate random numbers between -5.0 and 4.99
112
d = float(std::rand() % 1000 - 500) / 100.f;
113
}
114
115
std::vector<float> sorted =
sorting::wiggle_sort::wiggleSort<float>
(data1);
116
117
displayElements
(sorted);
118
119
for
(uint32_t j = 0; j < data1.size(); j += 2) {
120
assert(data1[j] <= data1[j + 1] &&
121
data1[j + 1] >= data1[j + 2]);
// check the validation condition
122
}
123
124
std::cout <<
"Test 1 passed\n"
;
125
}
126
128
int
main
() {
129
test
();
130
return
0;
131
}
132
test
void test()
Definition
caesar_cipher.cpp:100
main
int main()
Main function.
Definition
generate_parentheses.cpp:110
displayElements
static void displayElements(const std::vector< T > &arr)
Utility function used for printing the elements. Prints elements of the array after they're sorted us...
Definition
wiggle_sort.cpp:86
sorting
for working with vectors
wiggle_sort
Functions for Wiggle Sort algorithm.
sorting::wiggle_sort::wiggleSort
std::vector< T > wiggleSort(const std::vector< T > &arr)
Function used for sorting the elements in wave form.
Definition
wiggle_sort.cpp:54
sorting
wiggle_sort.cpp
Generated by
1.18.0