簡體   English   中英

用C對數字數組進行排序

[英]Sorting array of numbers in C

// code to sort array of 16 numbers, but output isnt quite correct.
// must use pointers to array addresses
// final output is -451 993 384 201 89 77 38 28 16 12 7 1 0 -2 -5 -17
// as you can see -451 isn't in the right place.

輸出

-451 7 993 1 0 16 -5 12 89 28 77 384 -2 38 -17 201

-451 -17 993 7 1 16 0 12 89 28 77 384 -2 38 -5 201

-451 993 -17 7 1 16 0 12 89 28 77 384 -2 38 -5 201

-451 993 7 -17 1 16 0 12 89 28 77 384 -2 38 -5 201

-451 993 7 1 -17 16 0 12 89 28 77 384 -2 38 -5 201

-451 993 16 7 1 -17 0 12 89 28 77 384 -2 38 -5 201

-451 993 16 7 1 0 -17 12 89 28 77 384 -2 38 -5 201

-451 993 16 12 7 1 0 -17 89 28 77 384 -2 38 -5 201

-451 993 89 16 12 7 1 0 -17 28 77 384 -2 38 -5 201

-451 993 89 28 16 12 7 1 0 -17 77 384 -2 38 -5 201

-451 993 89 77 28 16 12 7 1 0 -17 384 -2 38 -5 201

-451 993 384 89 77 28 16 12 7 1 0 -17 -2 38 -5 201

-451 993 384 89 77 28 16 12 7 1 0 -2 -17 38 -5 201

-451 993 384 89 77 38 28 16 12 7 1 0 -2 -17 -5 201

-451 993 384 89 77 38 28 16 12 7 1 0 -2 -5 -17 201

-451 993 384 201 89 77 38 28 16 12 7 1 0 -2 -5 -17

交易所總數:68

#include <stdio.h>

#define N 16

int xchg();

int main() {
    int numbers[16] = {7, 1, 993, -5, 0, 16, -451, 12, 89, 28, 77, 384, -2, 38, -17, 201}; 
    int cntr, cntr2, cntr3;
    int chgNum;

    for(cntr = 0; cntr < N; cntr++){
        for(cntr2 = 1; cntr2 < N; cntr2++){
            chgNum += xchg(&numbers[cntr], &numbers[cntr2]);
        }
        for(cntr3 = 0; cntr3 < N; cntr3++){
            if(cntr3 == 15){
                printf("%d", numbers[cntr3]);
            }
            else {
                printf("%d ", numbers[cntr3]);
            } 
        }

        printf("\n");


    }
    printf("total exchanges: %d\n", chgNum);
    return 0;
}

int xchg(int *p1, int *p2) {
    int tmp = 0;
    if(*p2 < *p1){
        tmp = *p1;
        *p1 = *p2;
        *p2 = tmp;
        return 1;
    }
    else {
        return 0;
    }
}

您需要更改main的循環。

for(cntr2 = cntr+1; cntr2 < N; cntr2++){

您可能還想檢查xchg是否為您提供升序/降序排序方向,或者您是否需要反轉交換條件。

另外:您忘記將chgNum初始化為零。

好的,問題是內部 for 循環從 1 開始,在第一次迭代后它會出錯,它需要從第一個循環所在的位置開始,即 cntr2 = cntr。

其他一些事情:

  • `xchng` 函數的前向聲明不正確。
  • if else 打印語句不執行任何操作,無論如何它都會打印相同的內容。
  • 如果您使用 `++` 運算符遞增一個數字並且它沒有被分配給任何東西,請始終使用 `++(int)`,它需要更少的操作。
  • 最后,還有一些令人討厭的變量名稱,更具描述性也無妨。 您還定義了一個宏,它是數組的大小,但您沒有使用它定義數組, int numbers[N] 會更有意義,因為至少您可以看到為什么在循環中使用宏。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM