Warm tip: This article is reproduced from serverfault.com, please click

c-如何计算冒泡排序中的掉期数量?

(c - How to count number of swaps in a bubble sort?)

发布于 2015-03-26 20:37:36

所以我需要我的程序打印输入的值并计算掉期数(不是比较数)。到目前为止,除交换计数器外,我一切正常。我尝试通过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;
}
Questioner
user4766244
Viewed
0
ProfOak 2015-03-27 05:10:35

你有一个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;
}