Skip to content

Instantly share code, notes, and snippets.

@courtneyfaulkner
Created September 6, 2017 04:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save courtneyfaulkner/cbef673af735d664f01b5ea5436d069c to your computer and use it in GitHub Desktop.
Save courtneyfaulkner/cbef673af735d664f01b5ea5436d069c to your computer and use it in GitHub Desktop.
[ZigZag] #practice
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