public class ZigZag {
public static void main(String[] args) {
int arr[] = new int[]{4, 3, 7,7, 8, 6, 2, 1};
zigzag(arr);
}
public static void zigzag(int[] arr) {
boolean flag = true ;//<
for(int i=0;i<arr.length-1;i++) {
if(flag) {
if(arr[i]>arr[i+1]) {
int temp = arr[i];
arr[i]=arr[i+1];
arr[i+1] = temp;
}
}else {
if(arr[i]< arr[i+1]) {
int temp = arr[i];
arr[i]=arr[i+1];
arr[i+1] = temp;
}
}
flag = !flag;
}
System.out.println(Arrays.toString(arr));
}
}
output: [3, 7, 4, 8, 6, 7, 1, 2]
public static void main(String[] args) {
int arr[] = new int[]{4, 3, 7,7, 8, 6, 2, 1};
zigzag(arr);
}
public static void zigzag(int[] arr) {
boolean flag = true ;//<
for(int i=0;i<arr.length-1;i++) {
if(flag) {
if(arr[i]>arr[i+1]) {
int temp = arr[i];
arr[i]=arr[i+1];
arr[i+1] = temp;
}
}else {
if(arr[i]< arr[i+1]) {
int temp = arr[i];
arr[i]=arr[i+1];
arr[i+1] = temp;
}
}
flag = !flag;
}
System.out.println(Arrays.toString(arr));
}
}
output: [3, 7, 4, 8, 6, 7, 1, 2]
No comments:
Post a Comment