c - 如何计算冒泡排序中的交换次数?

标签 c arrays function sorting swap

所以我需要我的程序来打印输入的值并计算交换次数(而不是比较)。到目前为止,除了交换计数器之外,一切都正常。我尝试在 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/

相关文章:

C 在头文件中定义一个指向 extern 函数的宏函数

java - 在 Java 中使用 C 代码的快速步骤

java - 传递和修改全局数组

function - 命名方法和命名函数的定义是什么?

c - 获取目录中文件的大小

c - 将应用程序预处理器信息转发到静态库

Javascript JSON 解析错误

c - C程序中如何存储变量值?

r - 编写创建列的 R 函数

c - 如何将位数组的元素传递给C中的函数