执行以下代码后,我得到了数组超出范围的异常:

时间:2019-09-26 19:29:58

标签: java sorting

我正在尝试执行冒泡排序,并将数组降序排列:

public void sortDescending(Cities arr[], int n) {
    String temp[]; //stores sorted array
    temp = new String[n];
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < n; j++) {
            int len1 = arr[j].name.length();
            int len2 = arr[j + 1].name.length();
            if (len1 < len2) {
                temp[j] = arr[j + 1].name;
                temp[j + 1] = arr[j].name;
            }
        }
    }
}

1 个答案:

答案 0 :(得分:0)

public void sortDescending(Cities arr[], int n){
    String temp[]; //stores sorted array
    temp = new String[n];
    for(int i=0;i<n;i++){
        for(int j=0;j<n-1;j++){//change this code as its checking array for j and j+1. so if you run you loop till n it will check array for n+1 hence array index out of bound error
        int len1 = arr[j].name.length();
        int len2 = arr[j+1].name.length();
        if(len1 < len2 ){
            temp[j] =  arr[j+1].name;
            temp[j+1] = arr[j].name;
        }
    }
 }

//对于气泡排序,请使用以下代码

void bubbleSort(Cities arr[], int n)
{
    //int n = arr.length;
    for (int i = 0; i < n-1; i++)
        for (int j = 0; j < n-i-1; j++)
            if (arr[j] > arr[j+1])
            {
                // swap temp and arr[i]
                int temp = arr[j];
                arr[j] = arr[j+1];
                arr[j+1] = temp;
            }
}

如果需要从此函数返回的任何东西,只需返回array。 您不必为气泡排序创建临时数组