0

Unable to figure out the problem in the code It says Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 6 I have gone through it a lot of times,still unable to figure whats wrong

Note: Trying to sort 0, 1 in an array

public class javaarray {

    public static void main(String[] args) {

        int[] arr = new int[]{1, 0, 0, 1, 1, 0}; 
        int left = 0, right =arr.length-1;
        while(left<right) {
            while(arr[left]==0 && left<right) {
                left++;
            }
            while(arr[right]==1 && left<right){
                right++;
            }
            if(left<right) {
                arr[left]=0;
                arr[right]=1;
                left++;
                right--;
              }  
           }

           for(int i=0; i<arr.length;i++) {
               System.out.print(arr[i]) 
           }
       }
    }

}
Riajur Rahman
  • 1,976
  • 19
  • 28

3 Answers3

0

These lines

while(arr[right]==1 && left<right){
  right++;
}

should be

while(arr[right]==1 && left<right){
  right--;
}
RaffleBuffle
  • 5,396
  • 1
  • 9
  • 16
0

If it's just 0-1 array, you should count zeros and ones in it and print all the ones after all the zeros:

    int[] arr = new int[]{1,0,0,1,1,0};
    int zerosCount = 0;
    for (int e: arr) {
        if (e == 0) {
            ++zerosCount;
        }
    }
    for (int i = 0; i < zerosCount; ++i) {
        System.out.print(0);
    }
    for (int i = zerosCount; i < arr.length; ++i) {
        System.out.print(1);
    }

This approach has linear complexity.

0

A more efficient approach (only valid for arrays which contain 0's and 1's):

int[] arr = new int[]{1, 0, 0, 1, 1, 0};
int current = 0;
int total = 0;

while (current < arr.legth) {
    total += arr[current];
    current++;
}

current = 0;
int[] sortedArr = new int[arr.length];

while (current < sortedArr.legth) {
    if (current < sortedArr.legth - total) {
        sortedArr[current] = 0;
    } else {
        sortedArr[current] = 1;
    }
}

for (int i = 0; i < sortedArr.length; i++) {
    System.out.print(sortedArr[i]) 
}
bra_racing
  • 622
  • 1
  • 8
  • 32