-1

when I run the following program which is to create a random array of integers and then sort them in www.jdoodle.com, I get this error message:


arr = [18, 85, 93, 81, 8, 7, 18, 26, 46, 41, 69, 48, 50, 16, 3, 26, 27, '\nā€™      31, 47, 71]

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 20
    at Sort.sortArray(Sort.java:35)
    at Sort.main(Sort.java:10)
Command exited with non-zero status 1

I just can't find this damn bug. Maybe some of you more experienced out there can take a look at the code? Thanks a lot!

=========================================================================

import java.util.Random;
import java.util.Arrays;

public class Sort {

    public static void main(String[] args) {
        int[] arr = createArray(20);
        System.out.println("arr = " + java.util.Arrays.toString(arr));

        int[] sortArr = sortArray(arr);
        System.out.println("sorted arr = " + '\n'
        java.util.Arrays.toString(sortArr));
    }

    public static int[] createArray(int l) {
        int[] vektor = new int[l];
        for(int i = 0; i < vektor.length; i++) {
            java.util.Random r = new java.util.Random();
            int n = r.nextInt(100);
            vektor[i] = n;
        }
        return vektor;
    }

    public static int[] sortArray(int[] inArr) {
        int a[] = inArr;
        int i, j, min, help = 0;
        int minPos = a.length;
        for(i = 0; i < a.length; i++) {
            min = a[i];
            for(j = 1; j < a.length - i; j++) {
                if(a[j] < min) {

                    minPos = j;
                }
                help = a[minPos]; // <--- Line 35
                a[minPos] = a[i];
                a[i] = help;
            }
        }
        return a;
    }

}
OldCurmudgeon
  • 64,482
  • 16
  • 119
  • 213

2 Answers2

1

This line:

System.out.println("sorted arr = " + '\n'
        java.util.Arrays.toString(sortArr));

You're missing a + between \n and java.util.Arrays.toString(sortArr).


Besides the example error, you equate minPos to a.length, which is equals to 20.
If your code doesn't enter in the if(a[j] < min), then a[minPos] will be the same as a[20], which is wrong: your array have 20 positions, starting from 0 to 19. The last one should be a[19].
You can achieve that with:
int minPos = a.length - 1;
KL_
  • 1,503
  • 1
  • 8
  • 13
1

You have:

int minPos = a.length;
...
    help = a[minPos];

So if none of the code between those two lines changes minPos then you'll get this error.

You may mean:

int minPos = a.length - 1;
OldCurmudgeon
  • 64,482
  • 16
  • 119
  • 213