11.09.2020 / 11:45 | |
hannah17 Пользователь Сейчас: Offline
Имя: Hannah Регистрация: 11.09.2020
| Hey, I am trying to implement bubble sort using recursion and have got a response ArrayIndexOutOfBoundsException: 11
Unable to figure out where I went wrong.. public static int[] recBubSort(int []arr, int n){
if(n > arr.length-1){
return arr;
}
if(arr[n] > arr[n+1]){
swap(arr,n,n+1);
}
return recBubSort(arr,n+1);
}
public static void swap(int arr[], int minPos, int index) {
//System.out.println("SelectionSort SWAP...");
int temp = arr[minPos];
arr[minPos] = arr[index];
arr[index] = temp;
}
|
11.09.2020 / 13:09 | |
Ксакеп Модератор форума Сейчас: Offline
Регистрация: 20.06.2012
| hannah17, hello. You should use some ideas from contract programming. Every function has a contract: a set of preconditions and postconditions that must be completed to ensure the function works as expected. For swap it may look like this: – 0 <= minPos <= arr.length - 1– 0 <= index <= arr.length - 1Contacts may be applied even to loops or if-conditions: public static int[] recBubSort(int[] arr, int n) {
if (n > arr.length - 1) {
return arr;
}
// here n <= arr.length - 1
// arr[n + 1] should work,
// thus n + 1 <= arr.length - 1
// thus n <= arr.length - 2
// but we have n <= arr.length - 1 from the contract above
if (arr[n] > arr[n + 1]) {
// indeed, if we have n == arr.length - 1
// arr[n + 1] === arr[arr.length] – OutOfBounds
swap(arr, n, n + 1);
}
return recBubSort(arr, n + 1);
}
|
12.09.2020 / 14:11 | |
hannah17 Пользователь Сейчас: Offline
Имя: Hannah Регистрация: 11.09.2020
| Awesome, thanks for helping out |
12.09.2020 / 14:19 | |
hannah17 Пользователь Сейчас: Offline
Имя: Hannah Регистрация: 11.09.2020
| Цитата Ксакеп: hannah17, hello. You should use some ideas from contract programming. Every function has a contract: a set of preconditions and postconditions that must be completed to ensure the function works as expected.This site has very well explained the concept of bubble sort: https://www.interviewbit.com/tutorial/bubble-sort/Please could you recommend any more resources you've been referring. |
13.09.2020 / 12:07 | |
Ксакеп Модератор форума Сейчас: Offline
Регистрация: 20.06.2012
| |