所以我需要我的程序打印输入的值并计算掉期数(不是比较数)。到目前为止,除交换计数器外,我一切正常。我尝试通过swap++;
在if语句中使用冒号排序来进行递增,但这是行不通的。有任何想法吗?这是我的代码。
#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
。你只需要运行一次sort函数,除非它不是第一次进行排序。
#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;
}
好,谢谢。如果我想计算调用“ sort”功能的时间,我该怎么办?
@Cryptic,您只需要打
sort()
一次电话int totalSwaps = sort(numArray, counter);
它被称为一次:-)我的意思是,如果
sort
不使用该如何终止程序?@ProfOak。您为什么要运行不排序的排序程序?