【发布时间】:2015-05-27 12:38:24
【问题描述】:
我的程序应该对文件中的数据进行排序。但是输出显示还没有完成排序,如下图:
123 约翰 512
121 史密斯萨姆 1022
163 BeamJim 2023
183 丹尼尔斯杰克 2932
323 贝利吉姆 922
0 0 0
我很确定我的冒泡排序函数是正确的。但是我不知道为什么它在完成之前就停止了交换。
second 问题为零出现在我的输出末尾。它应该只有 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()中,一旦您交换了员工ID,请确保您也交换了struct emp的其他成员。喜欢他们的first and last name, salary -
其次,
sortit()应该在for loop()之外调用,而不是每次添加员工的详细信息时 -
@SantoshA - 是的,我会的。在交换 struct emp 的其他成员之前,我试图先解决这个问题。感谢您的建议。
标签: c bubble-sort