-
Notifications
You must be signed in to change notification settings - Fork 0
/
WAVE_ARRAY.java
65 lines (50 loc) · 1.66 KB
/
WAVE_ARRAY.java
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
64
65
# Wave_array
## Time complexity- O(n)
//{ Driver code starts
import java.io.*;
import java.util.*;
class GFG {
public static void main (String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int t = Integer.parseInt(br.readLine().trim()); //Inputting the testcases
while(t-->0)
{
int n = Integer.parseInt(br.readLine().trim());// taking size of array
int arr[] = new int[n]; // declaring array of size n
String inputLine[] = br.readLine().trim().split(" ");
for(int i=0; i<n; i++){
arr[i]=Integer.parseInt(inputLine[i]); // input elements of array
}
Solution obj = new Solution();
obj.convertToWave(arr, n);
StringBuffer sb = new StringBuffer();
for (int i = 0; i < n; i++)
sb.append(arr[i] + " ");
System.out.println(sb); // print array
}
}
}
// } Driver Code Ends
class Solution{
// arr: input array
// n: size of the array
//Function to sort the array into a wave-like array.
public static void convertToWave(int arr[], int n){
int t=0;
for(int i=0;i<n;i+=2)//it will work for even indexes and check their values
{t=0;
if(i>0&&arr[i-1]>arr[i])//for one place ahead of even index
{
t=arr[i];
arr[i]=arr[i-1];
arr[i-1]=t;
}
if(i<n-1&&arr[i]<arr[i+1])//for one place after the index
{t=0;
t=arr[i];
arr[i]=arr[i+1];
arr[i+1]=t;
}
}
}
}