【问题标题】:Error: Out of bounds Java Bubble sort错误:Java 冒泡排序越界
【发布时间】:2014-06-03 14:28:34
【问题描述】:
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. 

    }
}

//以上是错误标记为越界。这可能是我想念的非常简单的东西,由于逻辑正确,我不相信它是它自己的冒泡排序功能?但是,对于未在我的堆栈中编程的冷凝可能是出站错误,如果是这种情况,我将不得不使用堆栈和其他一些方法更新此帖子。 -----感谢您的帮助,

【问题讨论】:

  • +1 因为计算机科学中的两个hardest problems 是缓存失效、命名事物和非一错误。

标签: java sorting indexoutofboundsexception


【解决方案1】:

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

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.

【讨论】:

  • 假设是这样,请accept我的回答。否则,请发布您为修复它所做的工作 - 并接受。
【解决方案2】:

当您调用 numbers[j+1] 时,您将超出数组范围。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-04-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-19
    • 2014-06-25
    • 2017-06-17
    相关资源
    最近更新 更多