附件是开发的合并排序代码,它能够计算给定数组的比较并打印出每个比较。我希望它能够有效地防止用户学习,以便比较的数字足够间隔,其中人们也不记得看过去的数字。现在我们需要让它以不同的顺序进行那些比较。代码可能不再漂亮和递归,但我预计会有一些巨大的丑陋循环。
public class MyMergeSort {
private int[] array; //array declared
private int[] tempMergArr; //temporary array
private int length; //counting length of array
private int ncompare=0;
public static void main(String a[]){
int[] inputArr = {9, 2, 56, 5, 4, 6, 60, 8, 1, //the array, given 60
32, 21, 12, 42, 57, 15, 16, 50, 18, 19,
20, 11, 34, 23, 48, 25, 26, 27, 51, 29,
30, 31, 10, 33, 22, 35, 39, 37, 38, 36,
40, 41, 13, 43, 44, 53, 46, 47, 24, 49,
17, 28, 52, 45, 54, 55, 3, 14, 58, 59,
7};
MyMergeSort mms = new MyMergeSort(); //declaring the merge sort for the array
mms.sort(inputArr);
System.out.print("\n\n");
for(int i:inputArr){
System.out.print(i);
System.out.print(" ");
}
System.out.print("\n Number of comparisons "+mms.ncompare+"\n");
}
public void sort(int inputArr[]) { //sort method uses 'this' for array input
this.array = inputArr;
this.length = inputArr.length;
this.tempMergArr = new int[length];
doMergeSort(0, length - 1);
}
private void doMergeSort(int lowerIndex, int higherIndex) { //indexed method for merge sort, states each step and case
if (lowerIndex < higherIndex) {
int middle = lowerIndex + (higherIndex - lowerIndex) / 2;
// Below step sorts the left side of the array
doMergeSort(lowerIndex, middle);
// Below step sorts the right side of the array
doMergeSort(middle + 1, higherIndex);
// Now merge both sides
mergeParts(lowerIndex, middle, higherIndex);
}
}
private void mergeParts(int lowerIndex, int middle, int higherIndex) { //merge method using 'for' case,
for (int i = lowerIndex; i <= higherIndex; i++) {
tempMergArr[i] = array[i];
}
int i = lowerIndex; //declaring index variables for different cases
int j = middle + 1;
int k = lowerIndex;
while (i <= middle && j <= higherIndex) { //define loops for steps of different cases
System.out.print(" C "+i+" "+j);
ncompare=ncompare+1;
if (tempMergArr[i] <= tempMergArr[j]) {
array[k] = tempMergArr[i];
i++;
} else {
array[k] = tempMergArr[j];
j++;
}
k++;
}
while (i <= middle) {
array[k] = tempMergArr[i];
k++;
i++;
}
}
C 0 1 C 2 3 C 0 2 C 1 2 C 1 3
这是我现有算法中的前五个比较。我想阻止它比较0和2然后比较1和2,因为用户可能会记住2,就像比较1和2然后1和3一样,用户会记住1。
我想这样做,以便比较的数字不会让用户感到难忘,以防止他们进行有偏见的比较
答案 0 :(得分:1)
比较顺序由合并排序算法定义。如果您在不可预测的情况下比较索引,或者不记得&#34;顺序,你不再进行合并排序了。你真的必须发明一种新的排序算法来实现这种行为。
但是,您可以在正常执行后以随机顺序打印比较。只需将它们存储在列表字段中,然后在排序后进行随机播放和打印。例如:
public List<int[]> comparisons = new ArrayList<>();
将mergeParts
中的字体替换为:
comparisons.add(new int[] { i, j });
排序后:
mms.sort(inputArr);
Collections.shuffle(mms.comparisons);
for (int[] c : mms.comparisons) {
System.out.print(" C "+c[0]+" "+c[1]);
}