假设 isAscSorted 函数符合预期(已测试) 我在这里做了一些愚蠢的事情,这就是为什么随机交换永远不会对数组进行排序 - 因为它每次只在不同的数组上进行 1 次交换?
我的测试用例是 int[] 值 1 = 新 int[] { 50, 10, 20, 4, 5, 1, 5 };
提示?
public static boolean isAscSorted (int[] arr){
for (int i=0; i<arr.length-1; i++){
if (arr[i]> arr[i+1]){
return false;
}
}
return true;
}
public static boolean swap(int[]a,int i,int j)
{
if (i == j){
return false;
}
int temp=a[i];
a[i]= a[j];
a[j]=temp;
return true;
}
static int randomSort(int[] values) {
//Ok Array is empty or null
if( values == null || values.length==0){
return 0;
}
boolean isSorted = false;
int steps = 0;
Random r = new Random();
int limit = values.length-1; //SOL: should be int limit = values.length;
while (!isAscSorted(values)){
//choose 2 random positions
int r1 = r.nextInt(limit);
int r2 = r.nextInt(limit);
//swap returns true if successful
boolean swapRes = swap(values, r1,r2);
//increment steps counter
if (swapRes)
steps++;
}
return steps;
}
最佳答案
该错误与随机的使用有关。 我已经指出 int limit = value.length-1; 这意味着最后一个数组位置永远不会交换,因此数组永远无法排序(除非第二个和最后一个数字相同且最大)。
关于java - 随机排序不会终止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46961651/