c - 快速排序功能仅在最后一个值最大时才有效

标签 c arrays sorting struct

我正在尝试在 C 中练习使用快速排序。我的程序是一个简单的结构数组,它接受命令行参数(name1 age 1 name2 age2 ...等)并按降序输出所述年龄。

仅当最后输入的年龄最大时,它才能正常工作。除此之外,我要么没有输出,要么出现 Seg Fault 11。有人有什么想法吗?

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define NameLen 80
void print_struct();

struct people
{
char name [NameLen + 1];
int age;
}; //defining a structure//

typedef struct people PERSON;
void quicksort(struct people list[],int,int);
int main(int argc, const char * argv[])

{
int i,j;
j = 0;
int l = ((argc/2)-1);


struct people list[l]; //maximum size of array of structs


   if (argc %2 == 0) //if the number of arguments is an even number
{

printf("Invalid Arguments!\n");
printf("Usage : ./hw5 name1 age1 name2 age2 ... "); //print error message and correct program usage
    exit(0);
}

printf("You have entered %d persons(s) into the program \n",(argc/2));

for (i=1; i < argc; i+=2)

{
    strcpy(list[j].name, argv[i]);
    list[j].age = atoi(argv[i+1]);
    if(list[j].age == 0)
    {
        printf("...Invalid age <=0. Try again.\n");

        exit(0);
    }
    j++;

}
   printf("Unsorted Names: \n");
    print_struct(&list,argc);

printf ("Sorted by Age: \n");
quicksort(list,0 ,j);
for(i=0;i<j;i++){
  printf("Name : %s| Age : %d\n", list[i].name, list[i].age);}//possible error here?

//Quicksort Function

最佳答案

也许问题出在j的值上。 j 是列表的长度吗?或者列表的长度 - 1?

这似乎是您想要的: j = 列表长度

printf ("Sorted by Age: \n");
quicksort(list,0 ,j-1);
for(i=0;i<j;i++){
  printf("Name : %s| Age : %d\n", list[i].name, list[i].age);}

关于c - 快速排序功能仅在最后一个值最大时才有效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38256937/

相关文章:

使用 time 和 difftime 创建超时

algorithm - 合并两个部分(共同超定)的订购信息集

algorithm - 需要帮助以更有效的方式设计搜索算法

c++ - 带 C 链接的非外部函数

c - 在不使用数组或动态分配的情况下平滑输入数据

c - 段错误 - 错误分配?

Java多维数组程序问题

php - 根据键=>值对对数组进行排序

java - 如何显示数组中负数的个数?

ruby-on-rails - Ruby On Rails 3 问题排序查询结果