Java Program Question - MNC - Technical Interview
Here we are going to see a very Interesting and Complicated Java Programming Questions, which is asking in literally all MNC's Technical Interview's
Input : Array -- { 5,1,8,-5,-1,6,2,-2,45,-55,-9,-89,9 }
Output : Array -- { -89 -55 -9 9 -5 5 -2 2 -1 1 6 8 45 }
Program :
package com.array;
public class SortingArray {
public static void main(String[] args) {
int[] arr = {5,1,8,-5,-1,6,2,-2,45,-55,-9,-89,9};
for(int a: arr) {
System.out.print(a+" ");
}
System.out.println();
for(int i=0; i<arr.length; i++) {
for(int j=i; j<arr.length; j++) {
if(arr[i]>arr[j]) {
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
for(int i=0; i<arr.length; i++) {
if(arr[i] == 0)
continue;
for(int j=i; j<arr.length; j++) {
if(arr[i] == -arr[j]) {
int temp = arr[i+1];
arr[i+1] = arr[j];
arr[j] = temp;
for(int k=i+2; k<arr.length; k++) {
for(int m=k; m<arr.length; m++) {
if(arr[k]>arr[m]) {
int temp1 = arr[k];
arr[k] = arr[m];
arr[m] = temp1;
}
}
}
}
}
}
for(int a: arr) {
System.out.print(a+" ");
}
}
}
Here's the explanation,
Step - 1 : First we need to sort the given input array in Ascending order.
Step - 2 : Second we need to use same sorting logic, but we have to compare instead of checking the greater than and we have to change the right side value to negative because of we have change the positive number to negative for comparison.
Step - 3 : Then inside the same comparison for loops we need to sort the array again to ascending for interchanging the positive value next to the negative value.
That's it Guys, if you need more clarification Click here to Join our Telegram Channel...
Comments
Post a Comment