CC-20 : Sort number series as wave form.
Description:
Given a sorted input array of numbers, sort the numbers in form of waves such that num1 >= num2 <= num3 >= num4 <= num5>=num6<=num7 and so on..
Test cases and expected outputs:
| Input Parameters | Expected outputs |
|---|---|
| Array: 3, 4, 9, 12, 22, 24, 30, 41, | Number series sorted as wave form: 4, 3, 12, 9, 24, 22, 41, 30, |
Pseudocode:
numberSeriesAsWaves(nums):
| Sorted Integer array named nums is received as input parameter. |
| Iterate through nums using for loop with idx as iteration variable and values of idx ranging from 0 to nums.length-1:
Swap nums[idx] and nums[idx+1].
|
| Return nums as it is sorted in wave form now. |
Code:
public int[] numberSeriesAsWaves(int[] nums){
for (int idx=0; idx < nums.length-1;idx=idx+2) {
int swap=nums[idx];
nums[idx]=nums[idx+1];
nums[idx+1]=swap;
}
return nums;
}
Click here to download and run code and test cases !
| About Us | Privacy Policy | Contact us |