简体   繁体   中英

Sorting questions..

Hello there I'm new to programming and I'm currently tasked to create a program relating to Sorting. and I keep getting the error

 Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -1
       at sorting.Sorting.main(Sorting.java:17)
 Java Result: 1 

The line it tells where the error is line 17 which contains:

 if (ArrayOfInts[j] > ArrayOfInts[j + 1])

please help.. heres the whole thing.

public class Sorting{
   public static void main(String[] args){
       int[] ArrayOfInts = {42, 97, 3, 689, 14, 1076, 3000, 8, 632, 327, 976, 4215};
       for(int i = ArrayOfInts.length; i >= 1; i--){
          for(int j = 0; j < i; j--){
            if (ArrayOfInts[j] > ArrayOfInts[j + 1]){
                int temp = ArrayOfInts[j];
                ArrayOfInts[j] = ArrayOfInts[j + 1];
                ArrayOfInts[j - 1] = temp;

            }
          }
       }
       for(int i = 0; i < ArrayOfInts.length; i++){
            System.out.println(ArrayOfInts[i] + " ");
       }
  }
}

When j=0 , this line is problematic:

ArrayOfInts[j - 1] = temp;

as you try to access -1 index in an array.

for(int i = ArrayOfInts.length; i >= 1; i--)

嗨,请用下面的行替换上面的代码行

for(int i = ArrayOfInts.length-1; i >= 0; i--)

I have made few correction to the code:
1. for 1st for loop, instead of int i = ArrayOfInts.length, use int i = ArrayOfInts.length-1, this is beacuse, length will return number of elements in array, and array is zero indexed hence in your case length will be 12 ie 0 to 11.
2.For 2nd for loop, instead of j- use j++ because j is starting from 0 to i.
3.instead of ArrayOfInts[j - 1] = temp; use ArrayOfInts[j + 1] = temp;

public static void main(String[] args)
    {
        int[] ArrayOfInts = {42, 97, 3, 689, 14, 1076, 3000, 8, 632, 327, 976, 4215};
        for(int i = ArrayOfInts.length-1; i >= 1; i--)
        {
            for(int j = 0; j < i; j++)
            {
                if (ArrayOfInts[j] > ArrayOfInts[j + 1])
                {
                    int temp = ArrayOfInts[j];
                    ArrayOfInts[j] = ArrayOfInts[j + 1];
                    ArrayOfInts[j + 1] = temp;

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM