我需要計算在四種不同的排序方法上發生的循環次數和比較次數。我正在使用「選擇」,「泡泡」,「插入」和「快速排序」方法。理想情況下,每次循環/比較時,我只需放置一個int,如loopCounter和++。雖然對於所有這些方面來說都很新穎,但我在區分需要包含這些計數器時遇到了困難。正如你將能夠看到下面的代碼,我試圖創建多個計數器。儘管如此,我認爲目前爲止只有選拔計數是正確的。計數循環和比較
此外,我需要計算一個值轉移的次數。換句話說,整數交換了多少次。
任何與此有關的幫助將不勝感激!
感謝
ArrayList<Integer> list = new ArrayList<Integer>();
//Counters for Selection Sort
int loopCounter = 0;
int compCounter = 0;
//Counters for Bubble Sort
int loopCounter2 = 0;
int compCounter2 = 0;
//Counters for Insertion Sort
int loopCounter3 = 0;
int compCounter3 = 0;
//Counters for Quick Sort
int loopCounter4 = 0;
int compCounter4 = 0;
public void selectionSort(Integer[] a) {
for(int i = 0; i < a.length; i++) {
int smallestValue = a[i];
int smallestIndex = i;
if(ascButton.isSelected()){
for(int j = i+1; j < a.length; j++) {
if (smallestValue > a[j]) {
smallestValue = a[j];
smallestIndex = j;
loopCounter++;
compCounter++;
}
}
a[smallestIndex] = a[i];
a[i] = smallestValue;
} else if(desButton.isSelected()){
for(int j = i+1; j < a.length; j++) {
if (smallestValue < a[j]) {
smallestValue = a[j];
smallestIndex = j;
loopCounter++;
compCounter++;
}
}
a[smallestIndex] = a[i];
a[i] = smallestValue;
}
}
}
public void bubbleSort(Integer[] a) {
int temp;
for (int i = a.length - 1; i > 0; i--) {
if(ascButton.isSelected()) {
for(int j = 0; j < i; j++) {
loopCounter2++;
compCounter2++;
if(a[j] > a[j + 1]) {
temp = a[j];
a[j] = a[j + 1];
a[j + 1] = temp;
}
}
} else if(desButton.isSelected()) {
for(int j = 0; j < i; j++) {
loopCounter2++;
compCounter2++;
if(a[j] < a[j + 1]) {
temp = a[j];
a[j] = a[j + 1];
a[j + 1] = temp;
}
}
}
}
}
public void insertionSort(Integer[] a) {
for(int i = 1; i < a.length; i++) {
loopCounter3++;
compCounter3++;
int temp = a[i];
int j = i - 1;
if(ascButton.isSelected()) {
while(j >= 0 && a[j] > temp) {
a[j + 1] = a[j];
j--;
}
a[j + 1] = temp;
} else if(desButton.isSelected()) {
while(j >= 0 && a[j] < temp) {
a[j + 1] = a[j];
j--;
}
a[j + 1] = temp;
}
}
}
public void quickSort(Integer[] a, int left, int right) {
int i = left;
int j = right;
int temp;
int pivot = a[(left + right)/2];
while(i <= j) {
if(ascButton.isSelected()) {
while(a[i] < pivot)
i++;
while(a[j] > pivot)
j--;
} else if(desButton.isSelected()) {
while(a[i] > pivot)
i++;
while(a[j] < pivot)
j--;
}
if(i <= j) {
temp = a[i];
a[i] = a[j];
a[j] = temp;
i++;
j--;
}
}
if(left < j) {
quickSort(a,left,j);
}
if(i < right) {
quickSort(a, i, right);
}
}
究竟是什麼不工作?你需要發佈所有的代碼來問什麼時候增加一些計數器?請用[mcve] –
問你的問題,我刪除了很多不太重要的代碼。雖然,正如我所說,我不確定在哪裏插入loopCounter ++和compCounter ++來正確計算每種排序方法的循環次數和比較次數。@ cricket_007 – Natecurt3030
如果你想要統計你循環的次數,那麼增加計數器是你在循環中做的第一件事。如果要計算比較值的次數,則每次執行比較值時遞增計數器。哪一部分不清楚? – Andreas