gpt4 book ai didi

C : Bubble sort did not finished swapping

转载 作者:行者123 更新时间:2023-11-30 21:10:35 25 4
gpt4 key购买 nike

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

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com