简体   繁体   中英

Array out of Bounds Bubble Sort

I keep getting index out of bounds error, and I don't know why. I feel like it shouldn't be out of bounds because number of pairs is one less than the number of list elements to begin with.

Here is my code:

`

    package main;

import java.util.Random;

import java.io.File;
import java.io.IOException;

import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;

import jxl.read.biff.BiffException;

import jxl.write.Label;
import jxl.write.Number;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import jxl.write.WriteException;

    public class BubbleSort 
    {

        static int Bubble_Sort_return_int (int[] list, int n)
        {   
            int comparison_count = 0;
            int number_pairs = n -1;
            boolean swapped_elements = true;
            while (swapped_elements == true)
                    {

                        for (int i = 1; i < number_pairs ; i++)
                        {   
                            swapped_elements = false;
                            comparison_count++;
                            if (list[i] > list[i-1])
                            {
                                int swap_element = list[i -1];
                                list[i-1] = list[i];
                                list[i] = swap_element;
                                swapped_elements = true;
                            }
                        }   

                        number_pairs = number_pairs - 1;
                    }
            return comparison_count;
        }

        public static void main (String args[])throws IOException, WriteException
        {
            Random one_to_ten = new Random();
            int list [][] = new int[1000][1000];
            int[] comparison_count_list_after_one_pass = new int[1000];
            for (int i = 0; i < 1000; i++)
            {
                for (int j = 0; j < i+1; j++)
                {
                    list[i][j] = one_to_ten.nextInt(10);
                }
            }
            for (int i = 0; i < 1000; i++)
            {
                comparison_count_list_after_one_pass[i] = Bubble_Sort_return_int(list[i], i + 1);       
            }
    }
    }

Your logic is flawed in Bubble_Sort_return_int . The first time called, n equals 1 , and number_pairs equals 0 . The comparison in the for loop ( i < number_pairs ) fails and number_pairs is decremented to -1 . This continues until number_pairs decrements from -2147483648 to 2147483647 . Only then does the for loop execute anything. At the point in the loop where i equals 1000 , list[i] causes the ArrayIndexOutOfBoundsException exception.

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