简体   繁体   中英

Having a problem with my mergeSort implementation

I'm getting an out of bounds error for my implementation of mergeSort , and I can't figure out why. This is the exact error message: Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 1 out of bounds for length 1"

Here's my implementation of mergeSort :

public static void mergeSort(int[] arr, int n) {
    if (n < 2) {
        return;
    }
    
    int mid_index = n / 2; 
    int[] left = new int[mid_index];
    int[] right = new int[n - mid_index];
    
    for (int i = 0; i < mid_index; i++) {
        left[i] = arr[i];
    }
    
    for (int i = mid_index; i < n; i++) {
        right[i - mid_index] = arr[i];
    }
    
    mergeSort(left, mid_index);
    mergeSort(right, n - mid_index);
    merge(arr, left, right, mid_index, n - mid_index);
}
    
public static void merge(int[] arr, int[] left, int[] right, int left_length, int right_length) {
    int i = 0;
    int j = 0; 
    int k = 0; 
    
    while (j < left_length && k < right_length) {
        if (left[i] < right[j]) {
            arr[k] = left[i];
            k++;
            i++;
        } else {
            arr[k] = right[j];
            k++;
            j++;
        }
    }
    
    while (j < left_length) {
        arr[k] = left[i];
        k++;
        i++;
    }
    
    while (i < right_length) {
        arr[k] = right[j];
        k++;
        j++;
    }
} 

The problem was in merge method. You make some mistakes with indexes. I corrected them in code below

public static void merge(int[] arr, int[] left, int[] right, int left_length, int right_length){
    int i = 0;//left
    int j = 0; //right
    int k = 0; 
    
    while(i<left_length && j < right_length){
        if(left[i] < right[j]){
            arr[k] = left[i];
            k++;
            i++;
        }
        else{
            arr[k] = right[j];
            k++;
            j++;
        }
    }
    
    while(i<left_length){
        arr[k] = left[i];
        k++;
        i++;
    }
    
    while(j<right_length){
        arr[k] = right[j];
        k++;
        j++;
        }
    } 

All 3 while loop in the merge method use the wrong index variables. The first loop while (j < left_length && k < right_length) { should be

    while (i < left_length && j < right_length) {

The second loop while (j < left_length) { should be

    while (i < left_length) {

Finally, the last loop while (i < right_length) { should be

    while (j < right_length) {

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