Exception in thread “main” java.lang.ArithmeticException: / by zero
at Main.swap(Main.java:42)
at Main.sort012(Main.java:18)
at Main.main(Main.java:68)
it is coming after executing
Exception in thread “main” java.lang.ArithmeticException: / by zero
at Main.swap(Main.java:42)
at Main.sort012(Main.java:18)
at Main.main(Main.java:68)
it is coming after executing
wrong answer showing
even after fixing my swap function.
@nagpalyash4 As we know x/0 is indefinite in maths. So your function is trying to divide something by 0 that’s why you are getting this exception.
This is my code wrong answer is coming.
import java.util.*;
public class Main {
public static void sort012(int[] arr , int n){
//Your code goes here
int low = 0;
int high = n-1;
int mid = 0;
while(mid<=high){
if(arr[mid]==0){
swap(arr[low] , arr[mid]);
low++;
mid++;
}
else if(arr[mid]==1){
mid++;
}
else{
swap(arr[mid] , arr[high]);
high--;
}
}
}
public static void swap(int x , int y){
x = x ^ y; // x now becomes 15 (1111)
y = x ^ y; // y becomes 10 (1010)
x = x ^ y; // x becomes 5 (0101)
}
public static void printArray(int[] arr) {
for (int element : arr) {
System.out.println(element);
}
System.out.println();
}
public static void main(String args[]) {
// Your Code Here
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int arr[] = new int[n];
for(int i=0;i<n;i++){
arr[i] = sc.nextInt();
}
sort012(arr , n);
printArray(arr);
}
}
@nagpalyash4 You might have learn that if you sent to variables to a function and swap them the swaping doesn’t get done. The swapping can only be done in an array by providing the indexes you want to swap.Corrected Code is Below :
import java.util.*;
public class Main {
public static void sort012(int[] arr , int n){
//Your code goes here
int low = 0;
int high = n-1;
int mid = 0;
while(mid<=high){
if(arr[mid]==0){
swap(arr,low ,mid);
low++;
mid++;
}
else if(arr[mid]==1){
mid++;
}
else{
swap(arr,mid , high);
high--;
}
}
}
//Swap function changed to swapping by using indexes
public static void swap(int[] arr,int x , int y){
//Swapping should be simple like this
int temp = arr[x];
arr[x] = arr[y];
arr[y] = temp;
}
public static void printArray(int[] arr) {
for (int element : arr) {
System.out.println(element);
}
System.out.println();
}
public static void main(String args[]) {
// Your Code Here
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int arr[] = new int[n];
for(int i=0;i<n;i++){
arr[i] = sc.nextInt();
}
sort012(arr , n);
printArray(arr);
}
}
I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.
On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.