Learn-dsa..in 30 days!



























CC-19 : Arrange array in waveform.

Description:

Given input integer array arr, arrange the array in wave form, ie element at index idx should be greater than element at index idx-1 and index idx+1.

Test cases and expected outputs:

Input Parameters Expected outputs
arr={1,2,3,4,5,6,7} 1,3,2,5,4,7,6
arr={ 0,-1,-2,-3,-4} -1,0,-3,-2,-4
arr={-33,-59,-4,0,77,21,67} -59,-4,-33,77,0,67,21
arr={ 5,4,7} 4,7,5

Pseudocode:

The java method should accept following input parameters: arr (int array).
Iterate through arr using a for loop and loop variable idx. Start the for loop from index 1 and increment idx by 2 for each iteration:
If arr[idx-1] > arr[idx], swap the same.
Check that idx+1 should be < arr.length. If arr[idx+1] > arr[idx], swap the same.
After above loop completes, array will be in wave form.

Code:

public int[] arrayArrayWaveForm(int[] arr) throws Exception{
	int temp=0;
	for (int idx=1; idx < arr.length; idx+=2) {
		if (arr[idx-1] > arr[idx]) {
			temp=arr[idx];
			arr[idx]=arr[idx-1];
			arr[idx-1]=temp;
		}
		if ((idx+1 < arr.length)&&(arr[idx] < arr [idx+1])) {
			temp=arr[idx];
			arr[idx]=arr[idx+1];
			arr[idx+1]=temp;
		}
	}	
	return arr;	
}

Click here to download and run code and test cases !