-4

I got "Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 6" error while i'm running this program.This code is to implement selection sort.please can someone help me.

package Sorting;

public class Selection {

    public static void sort(int[] array) {

        int min, temp;

        for (int i = 0; i <= array.length-1  ; i++) {
            min = i;
            for (int j = i+1; j <= array.length   ; j++) {
                if (  array[j]<array[min]) {
                    min = j;
                }

            }
            temp = array[min];
            array[min]=array[i];
            array[i] = temp;

        }
    }

    public static void main(String[] args) {
        int a[]  = {51,6,3,55,34,12 };
        sort(a);
        for (int i  :a) {
            System.out.println(a[i]);
        }
    }

}
John Kugelman
  • 349,597
  • 67
  • 533
  • 578
Sachin
  • 389
  • 5
  • 11

2 Answers2

0

Hey for each does not return index it's return value of each element so the end you should print below

for (int i  :a) {
            System.out.println(i);
        }
Anuj J Pandey
  • 656
  • 1
  • 4
  • 17
0

Here is the corrected code.

public class Selection {

    public static void sort(int[] array) {

        int min, temp;

        for (int i = 0; i <= array.length-1  ; i++) {
            min = i;
            for (int j = i+1; j <= array.length-1   ; j++) {
                if (  array[j]<array[min]) {
                    min = j;
                }

            }
            temp = array[min];
            array[min]=array[i];
            array[i] = temp;

        }
    }

    public static void main(String[] args) {
        int a[]  = {51,6,3,55,34,12 };
        sort(a);
        for (int i=0;i<a.length ;i++) {
            System.out.println(a[i]);
        }
    }

}

enter image description here