我的問題是,selectionsort顯示錯誤的交換次數。 它總是顯示0或一些大數字。 當給數組排序,它總是表現出大量或全部其他未分類測試始終爲0使用排序數組進行選擇排序需要多少次交換?
//this class is called selectionSort. It sorts a given array.
public class SelectionSort implements ISorter {
private int swaps;
public SelectionSort() {}
@Override
public ISortStats sort(int[] a) {
long time = System.nanoTime();
int swapping = 0;
int numOfComparisons = 0;
for (int i = 0; i < a.length; i++) {
int min = i;
for (int j = i + 1; j < a.length; j++) {
numOfComparisons++;
if (a[min] >= a[j]) {
min = j;
}
}
swapping = swap(a, i, min, this.swaps);
}
long endTime = System.nanoTime();
SortStats ss = new SortStats("Selection Sort",
a.length,
numOfComparisons,
swapping,
(endTime - time));
return ss;
}
private int swap(int[] a, int i, int j, int swapping) {
int temp = a[i];
a[i] = a[j];
a[j] = temp;
return swapping++;
}
}
這縮進......瘋了。 –
不再:) :)。 –
不完全確定,但這對我來說看起來很可疑:'swapping = swap(a,i,min,this.swaps);'。也許你的意思是'swap = swap(a,i,min,swapping);'? – Turing85