C : Bubble sort did not finished swapping

标签 c bubble-sort

我的程序应该对文件中的数据进行排序。但输出显示尚未完成排序,如下所示:

123 DoeJohn 512

121 史密斯萨姆 1022

163 BeamJim 2023

183 丹尼尔斯 jack 2932

323 贝利吉姆 922

0 0 0

我很确定我的冒泡排序功能是正确的。但我不知道为什么它在完成之前就停止了交换。

第二问题是零出现在我的输出末尾。应该只有5行数据。请指教?提前致谢。

#include <stdio.h>
#include <string.h>
#define MAX 100

/* Define Structure */
/* ---------------- */
struct emp
{
   int      id_num;     /* employee number */
   float    salary;     /* employee salary */
   char first_name[20]; /* employee first name */
   char last_name[30];  /* employee last name */
};

void sortit (struct emp*, int);

main () 
{


    /* Declare variables */
    /* ----------------- */
    struct emp info[100];   /* a maximum 100 people can be stored */
    FILE    *in_file_ptr, *out_file_ptr;
    int     i, count;
    char    filename[30];
    char    sort_by;

    /* Greetings */
    /* --------- */
    printf ("Welcome to Employee Center.\n");

    /* Prompt user for file name */
    /* ------------------------- */
    printf ("\nEnter file name: ");
    scanf ("%s", filename);
    fflush(stdin);


    /* Open the input file. If error, display message and exit  */
    /* --------------------------------------------------------------- */
    in_file_ptr = fopen(filename, "rb");
    if (!in_file_ptr)
    {
        printf ("\nCannot open file %s for reading.\n", filename);
        return 1;
    }


    for ( i = 0; i < 100; i++ )
    {
        /* Read data from input file and load array struct */
        /* ------------------------------------------------ */
        fread (&info[i], sizeof(info[i]), 1, in_file_ptr);


        sortit (info, count);

        /* Concatenate first name and last name string */
        /* ------------------------------------------ */    
        strcat  (info[i].last_name, info[i].first_name);

        printf ("%10i %20s %-10.2f\n", info[i].id_num, 
            info[i].last_name, info[i].salary);


        if(feof(in_file_ptr))break;

    } /* end for loop */

    fclose (in_file_ptr);

} /*end main */

void sortit (struct emp a[], int num)
/* takes a single dim array of int and sorts the array in place */
{
    int j, i, temp;


    /* This sorts the array - bubble sort */

    for ( j=0; j<num; j++ )
        for ( i=0; i<=num-1; i++ )
            if ( a[i].id_num > a[i+1].id_num )
            {
                temp = a[i].id_num;
                a[i].id_num = a[i+1].id_num;
                a[i+1].id_num = temp;   

            } /* end if */


} /* end sortit function */enter code here

最佳答案

sortit (struct emp a[], int num) 函数中更改第二个 for() 循环

for ( i=0; i<=num-1; i++ )

for ( i=0; i<num-1; i++ )

关于C : Bubble sort did not finished swapping,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29228607/

相关文章:

c 如何使用 memcpy 将十六进制值复制到数组中

c - 在冒泡排序中显示 2 个相同的值

c++ - 程序在冒泡排序时崩溃?

c - C 中的冒泡排序函数

java - 使用双向链接列表按优先级排序

将 Q18.2 转换为 float

c - Bash - 编译 sleep 可加载

c - C 中的不透明数据类型

c - 如何对 char 数组的数组使用指针?

Python - 冒泡排序