我想编写一个名为itisSorted
的方法(返回一个布尔值),它接受两个参数;
data
:整数数组n
:数组中元素的数量true
数组已排序,则返回data
。
public boolean itisSorted(int [] data, int n)
{
if(data.length ==0 || data.length==1)
return true;
else if (data[n] > data[n-1]) //here i compare the first two elements
return false;
else //here is where i put the recursive call to check if
// the rest of the array is sorted, but I am having difficulties with the
// part of the code
}
答案 0 :(得分:3)
我想你想要这样的东西
public static boolean itisSorted(int[] data, int n) {
// Null or less then 2 elements is sorted.
if (data == null || n < 2) {
return true;
} else if (data[n - 2] > data[n - 1]) {
// If the element before (n-2) this one (n-1) is greater,
return false;
}
// recurse.
return itisSorted(data, n - 1);
}
public static void main(String[] args) {
int [] data = {1,2,3};
System.out.println(Arrays.toString(data) //
+ (itisSorted(data, data.length) ? " Sorted" : " Unsorted"));
data = new int[] {3,2,1};
System.out.println(Arrays.toString(data) //
+ (itisSorted(data, data.length) ? " Sorted" : " Unsorted"));
}
答案 1 :(得分:1)
//使用此方法无需传递数组的长度
public static boolean isOrdered(int nums[])
{
// Base Cases
if (nums.length == 0)
return true;
if (nums.length == 1)
return true;
int[] temp = new int[nums.length - 1];
if (nums[0] <= nums[1]) {
for (int i = 1; i < nums.length; i++) {
temp[i-1] = nums[i];
}
return isSorted(temp);
} else
return false;
}
答案 2 :(得分:1)
使用递归的解决方案
int isArraySorted(int []a, int index)
{
if(index == 1 || a.length == 1)
return 1;
return (a[index -1] <= a[index-2]) ? 0 : isArraySorted(a, index-1) ;
}
相应地改变下降的条件。
答案 3 :(得分:0)
public boolean itisSorted(int [] data, int n)
{
if(data.length ==0 || data.length==1)
return true;
else if (data[n] > data[n-1]) //here i compare the first two elements
return false;
else
{
if(n==data.length-1)
{
return true;
}
return itisSorted(data, n+1); //recursion, checks next integer in the array
}
这是你想要的答案吗?