Skip to content

Commit a18b18b

Browse files
authored
Merge pull request #330 from ishan-pf/ishan-pf
WaveSort Question is added to the Sorting Algorithms Folder
2 parents 973a73b + fe86339 commit a18b18b

File tree

1 file changed

+73
-0
lines changed

1 file changed

+73
-0
lines changed

Sorting Algorithms/wavesort.cpp

Lines changed: 73 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,73 @@
1+
/*Given a sorted array arr[] of distinct integers. Sort the array into a wave-like array and return it
2+
In other words, arrange the elements into a sequence such that arr[1] >= arr[2] <= arr[3] >= arr[4] <= arr[5].....
3+
4+
Example 1:
5+
6+
Input:
7+
n = 5
8+
arr[] = {1,2,3,4,5}
9+
Output: 2 1 4 3 5
10+
Explanation: Array elements after
11+
sorting it in wave form are
12+
2 1 4 3 5.
13+
14+
Example 2:
15+
16+
Input:
17+
n = 6
18+
arr[] = {2,4,7,8,9,10}
19+
Output: 4 2 8 7 10 9
20+
Explanation: Array elements after
21+
sorting it in wave form are
22+
4 2 8 7 10 9.
23+
24+
25+
Expected Time Complexity: O(n).
26+
Expected Auxiliary Space: O(1).
27+
28+
Constraints:
29+
1 ≤ n ≤ 106
30+
0 ≤ arr[i] ≤107
31+
32+
33+
solution : */
34+
35+
#include<iostream>
36+
using namespace std;
37+
38+
// A utility method to swap two numbers.
39+
void swap(int *x, int *y)
40+
{
41+
int temp = *x;
42+
*x = *y;
43+
*y = temp;
44+
}
45+
46+
// This function sorts arr[0..n-1] in wave form, i.e., arr[0] >=
47+
// arr[1] <= arr[2] >= arr[3] <= arr[4] >= arr[5] ....
48+
void WaveSort(int arr[], int n)
49+
{
50+
// Traverse all even elements
51+
for (int i = 1; i < n; i+=2)
52+
{
53+
// If current even element is smaller than previous
54+
if ( arr[i-1] < arr[i] )
55+
swap(&arr[i], &arr[i-1]);
56+
57+
// If current even element is smaller than next
58+
if (arr[i] > arr[i+1] && i<= n-2 )
59+
swap(&arr[i], &arr[i + 1]);
60+
}
61+
}
62+
63+
64+
int main()
65+
{
66+
int arr[] = {10, 90, 49, 2, 1, 5, 23};
67+
int n = sizeof(arr)/sizeof(arr[0]);
68+
WaveSort(arr, n);
69+
for (int i=0; i<n; i++)
70+
cout << arr[i] << " ";
71+
return 0;
72+
}
73+

0 commit comments

Comments
 (0)