所以我需要我的程序来打印输入的值并计算交换次数(而不是比较)。到目前为止,除了交换计数器之外,一切都正常。我尝试在 if 语句中使用 swap++;
以及冒泡排序来增加,但这不起作用。有任何想法吗?这是我的代码。
#include <stdio.h>
int sort(int array[], int count);
int main(void) {
int numArray[100];
int counter, value;
printf("Enter array length \n");
scanf("%d", &counter);
int i = 0;
while(i < counter){
scanf("%d", &numArray[i]);
i++;
}
i = 0;
while(i < counter) {
sort(numArray, counter);
i++;
}
int totalSwaps = sort(numArray, counter);
printf("Swaps: %d\n", totalSwaps);
i = 0;
while(i < counter) {
printf("Values: %d\n", numArray[i]);
i++;
}
return 0;
}
int sort(int array[], int count) {
int i, j, temp;
int swaps = 0;
for(i = 0; i < count-1; ++i) {
for(j=0; j < count-1-i; ++j) {
if(array[j] > array[j+1]) {
temp = array[j+1];
array[j+1] = array[j];
array[j] = temp;
swaps++;
}
}
}
return swaps;
}
最佳答案
你有一个 while 循环来对它排序 count
次。您只需运行排序函数一次,除非它第一次没有排序。
#include <stdio.h>
int sort(int array[], int count);
int main(void){
int numArray[100];
int counter;
printf("Enter array length \n");
scanf("%d", &counter);
int i;
for (i = 0; i < counter; i++){
printf("%d. Enter a numner: ", i);
scanf("%d", &numArray[i]);
}
// How many times would you like to sort this array?
// You only need one sort
/*
i = 0;
while(i < counter){
sort(numArray, counter);
i++;
}
*/
int totalSwaps = sort(numArray, counter);
if (totalSwaps == 0) {
printf("The array is already in sorted order\n");
return 0;
}
printf("Swaps: %d\n", totalSwaps);
for (i = 0; i < counter; i++) {
printf("Values: %d\n", numArray[i]);
}
return 0;
}
int sort(int array[], int count){
int i, j, temp;
int swaps = 0;
for(i = 0; i < count-1; ++i){
for(j=0; j<count-1-i; ++j){
if(array[j] > array[j+1]){
temp = array[j+1];
array[j+1] = array[j];
array[j] = temp;
swaps++;
}
}
}
return swaps;
}
关于c - 如何计算冒泡排序中的交换次数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29288367/