【发布时间】:2015-03-26 20:37:36
【问题描述】:
所以我需要我的程序打印输入的值并计算交换次数(不是比较)。到目前为止,除了交换计数器之外,我已经完成了所有工作。我尝试通过在 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;
}
【问题讨论】:
标签: c arrays function sorting swap