我需要计算在四种不同的排序方法上发生的循环次数和比较次数。我正在使用“选择”,“泡泡”,“插入”和“快速排序”方法。理想情况下,每次循环/比较时,我只需放置一个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