错误:越界Java冒泡排序

时间:2014-04-19 02:04:19

标签: java sorting indexoutofboundsexception

public void sort()  // pulls the numbers off the stack then orders them, putting back onto stack in order. 
                    // Does not care where the it left off. Note: making a temp varible for the new head will head. 
                    // once the old head hits a -1; or a value less than it self it will start from the "sort head"
                    // ????????????????????????????????????????????????????????????????????????????????????????????????
{
     int[] numbers = new int[node - 1];    //everything else should be working fine. 

     for(int i = size ; i > 1; i--)        //for loop for the numberof/size of the elements needed to be sorted.3
     {
         int temphead = head;

         numbers[i] = (stack.getpeople(temphead));  // pulls a value for a stack

         temphead = stack.getBLink(temphead);       // pulls that values back link and adds it to the new lead.
     }

    int tempVar;

    for (int i = 0; i < numbers.length; i++) //used for bubble sort.
    {
             for(int j = 0; j < numbers.length - 1; j++) // used for bubble sort.
             {
                     if(numbers[i] > numbers[j + 1]) //ERROR HERE Out of bounds
                     {
                     tempVar = numbers [j + 1];      //ERROR HERE Out of bounds
                     numbers [j + 1] = numbers [i];  //ERROR HERE Out of bounds
                     numbers [i] = tempVar;          //ERROR HERE Out of bounds
                     }
             }
    }
    int temphead = head;

    for(int i = size ; i > 1; i--)
    {
        stack.getpeople(temphead = numbers[i]); //adds the sorted list back to the stack 
        temphead = stack.getBLink(temphead); //resets the temp head. 

    }
}

//上面的错误被标记为超出范围。它可能是我想念的非常简单的东西,我不相信它是自己的冒泡排序函数,因为逻辑是对的吗?但是它可能是一个出站错误对我的堆栈中没有编程的冷凝,如果是这种情况我将不得不用堆栈和一些其他方法更新这篇文章。 -----感谢您的帮助,

2 个答案:

答案 0 :(得分:2)

在你想到之前错误是一行 -

for(int j = 0; j < numbers.length - 1; j++) { // <--- The error was here.
  // used for bubble sort.
  if(numbers[i] > numbers[j + 1]) // When j = (number.length - 1) [0 based indexing], 
                                  // then j + 1 = (number.length) and that is 
                                  // out of bounds.

答案 1 :(得分:0)

当您拨打号码[j + 1]时,您将超出阵列的界限。