-2

am a beginner to java. Help me here am trying to do BubbleSorting and am getting exception in the main method.Please tell me where is the mistake i have done here.

package Programs;

import java.util.Scanner;
public class EBubleSorting {

@SuppressWarnings("resource")
public static void main(String[] args) {
     Scanner in = new Scanner(System.in);
     System.out.println("Enter the Size");
     int Size = in.nextInt();
     int [] array = new int[Size];
     int temp =0;
     System.out.println("Enter the elemnts of an Array");
     for (int i =0 ; i<Size ; i++)
     {
         array[i] = in.nextInt();
     }
     System.out.println("==============");
    // Bubble Sorting Starts 
     for (int ii =0 ; ii<Size ; ii++)
     {
        if(array[ii] > array[ii+1])
        {

            array[ii+1] = temp;
            System.out.println(array[ii+1]);
            array[ii+1] = array[ii];
            System.out.println(array[ii+1]);
            array[ii] = temp;
            System.out.println(array[ii]);
        }
        else if( array[ii] == array[ii+1]) 
        {

        }




     }


}


}
user207421
  • 305,947
  • 44
  • 307
  • 483

2 Answers2

2

Arrays are indexed from 0 to (array.length-1). That's the first problem. If you want to bubble sort an array, here's a code that might help you.

public static void bubbleSort(int[] arr) {
    boolean swapped = true;
    int j = 0;
    int tmp;
    while (swapped) {
        swapped = false;
        j++;
        for (int i = 0; i < arr.length - j; i++) {
            if (arr[i] > arr[i + 1]) {
                tmp = arr[i];
                arr[i] = arr[i + 1];
                arr[i + 1] = tmp;
                swapped = true;
            }
        }
    }
}
juliccr
  • 341
  • 3
  • 12
0

In this code

 for (int ii =0 ; ii<Size ; ii++)
 {
    if(array[ii] > array[ii+1])

when ii is equal to Size - 1 (the last item) then array[ii+1] will fail

if the array size is 4 as the data is

 array[0] = 2
 array[1] = 4
 array[2] = 3
 array[3] = 1

then when ii is 3 (the last item of the array), you can not access array [3 + 1] as this will be outside of the bounds of the array

Scary Wombat
  • 44,617
  • 6
  • 35
  • 64