Created
September 6, 2017 04:30
-
-
Save courtneyfaulkner/cbef673af735d664f01b5ea5436d069c to your computer and use it in GitHub Desktop.
[ZigZag] #practice
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class ZigZag { | |
/* | |
Example: | |
Input: arr[] = {4, 3, 7, 8, 6, 2, 1} | |
Output: arr[] = {3, 7, 4, 8, 2, 6, 1} | |
Input: arr[] = {1, 4, 3, 2} | |
Output: arr[] = {1, 4, 2, 3} | |
*/ | |
static void main(String[] args) { | |
println zigZag([4, 3, 7, 8, 6, 2, 1] as int[]) | |
println zigZag([1, 4, 3, 2] as int[]) | |
} | |
static int[] zigZag(int[] arr) { | |
boolean direction = true | |
int temp | |
for (int i = 0; i < arr.length - 1; i++) { | |
if (direction) { | |
if (arr[i] > arr[i + 1]) { | |
arr = swap(arr, i, i + 1) | |
} | |
} else { | |
if (arr[i] < arr[i + 1]) { | |
arr = swap(arr, i, i + 1) | |
} | |
} | |
direction = !direction | |
} | |
arr | |
} | |
static int[] swap(int[] arr, int pos1, int pos2) { | |
int temp | |
temp = arr[pos1] | |
arr[pos1] = arr[pos2] | |
arr[pos2] = temp | |
arr | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment