[英]Check if array is sorted using recursion
I am getting true as answer even for unsorted(isNonDescending) arrays. Where is the bug?即使对于 unsorted(isNonDescending) arrays,我的答案也是真实的。错误在哪里? I want to break the array into smaller problem from the start of the array only.我只想从数组的开头将数组分解成更小的问题。
//Check for isNonDescending. //检查isNonDescending。
public class AlgoAndDsClass {
public static void main(String args[]) {
int[] unsortedArry = { 1, 2, 3, 4 };
int[] unsortedArry2 = { 1, 2, 4, 3 };
System.out.println(isSorted(unsortedArry, unsortedArry.length));
System.out.println(isSorted(unsortedArry2, unsortedArry2.length));
}
private static boolean isSorted(int[] arr, int size) {
if (size == 0 || size == 1)
return true;
if (arr[0] > arr[1]) {
return false;
}
System.out.println(arr.length);
boolean smallwork = isSorted(arr, size - 1);
return smallwork;
}
you keep on checking the same 2 elements, try using the size variable instead as the arrray indexes.您继续检查相同的 2 个元素,请尝试使用 size 变量代替数组索引。 For exmaple, if the first 2 elements are sorted you'll get true, thats because you check only the first two elements in the arrray.例如,如果对前 2 个元素进行了排序,你会得到 true,那是因为你只检查数组中的前两个元素。
Instead of passing the size of the array as a parameter, which makes no sense anyway, because you can simply call arr.length
, you should pass a starting index and increase it with each recursive call until you have reached the length of your array.不要将数组的大小作为参数传递,这无论如何都没有意义,因为您可以简单地调用arr.length
,您应该传递起始索引并在每次递归调用时增加它,直到达到数组的长度。
private static boolean isSorted(int[] arr, int index) {
if(arr.length == 0 || arr.length == 1 || index == arr.length - 1){
return true;
}
if (arr[index] > arr[index + 1]) {
return false;
}
return isSorted(arr, index + 1);
}
and call from main with 0
as a starting index并以0
作为起始索引从 main 调用
System.out.println(isSorted(unsortedArry,0));
System.out.println(isSorted(unsortedArry2,0));
Array is sorted if the sub-array from the start and up to one element before last is sorted and the last element is larger or equal to the element before last one.如果从开始到最后一个元素的子数组已排序并且最后一个元素大于或等于最后一个元素之前的元素,则数组已排序。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.