如何并行对C中的字符串数组和整数数组进行排序?没有结构?

How to sort string array in C with integer array in parallel? Without structs?

好的,年龄的冒泡排序有效。我现在遇到麻烦的部分是需要首先发生的全名的冒泡排序。 我考虑过将排序后的年龄临时存储在一个数组中,但我想那是作弊。 我需要数据输入,打印未排序的姓名和年龄,排序姓名,打印排序的姓名未排序的年龄,排序年龄,打印排序的姓名和年龄...

我该怎么办?

  1. 字符串数组排序成功了吗?
  2. 用相应的字符串保留适当的年龄?
  3. 打印排序后的字符串而不同时对年龄和字符串进行排序?

    #define SIZE 5
    #include <stdio.h>
    #include <string.h>
    #include <stdio.h>
    
    
    void input(char fullname[][25], int age[]);
    void output(char fullname[][25], int age[]);
    //int compare(int x, int y);
    void bubbleSortage(int * const array,const int size);
    
    int main(int argc, char *argv[]) 
    {
        char fullname[SIZE][25];
        int age[SIZE];
        int unneccessayalternateagearraybecausewehavetoprintthesortedvaluestwice[SIZE];
    
        // prompt user for names and ages
        input(fullname, age);
        //output unsorted names and ages
        output(fullname, age);
    
        bubblesortname(fullname,SIZE);
    
        output(fullname, age);
    
        //sorts age
        bubbleSortage(age,SIZE);
        //
        output(fullname, age);
    
    
        return 0;
    }
    
    void input(char fullname[][25], int age[]) 
    {
        int i;
        for (i = 0; i < SIZE; i++) 
        {
            fflush(stdin);
            printf("Enter a full name\n");
            //scanf("%[\^n]\n", fullname[i]);
            fgets (fullname[i],40, stdin);
            printf("Enter the age\n");
            scanf("%d", &age[i]);
    
        }
    }
    
    void output(char fullname[][25], int age[]) 
    {
        int i;
        for (i = 0; i < SIZE; i++)
            printf("%s, %d\n", fullname[i], age[i]);
    }//end function
    
    void bubblesortname(int * const array, const int size)
    {
        int i, j;
    
    
        for (j = 0; j < size -1; j++) 
        {
            for (i = 0; i < size -1; i++) 
              {
                if (0<strcmp(fullname[i + 1], fullname[i]))
                 {
                    char *temp = fullname[i];
                    fullname[i]= fullname[i+1];
                    fullname[i+1]= tmp;
    
    
                 }//end if
    
            }//end inner for
    
        }//end for
    
    }//end function
    
    void bubbleSortage(int * const array, const int size)
    {
        void swap(int *element1Ptr, int *element2Ptr );
        int pass; //pass counter
        int j; // comparison counter
    
        //loop to control passes
        for(pass = 0;pass < size -1; pass++)
        {
            //loop to control comparison each pass
            for(j=0; j<size - 1;j++)
            {
                //swap elements if they are not in order
                if(array[j]>array[j+1])
                {
                    swap(&array[j], &array[j+1]);
                }// end if
    
            }// end inner for
    
        }// end outer for
    
    
    }// end function
    
    //swap values at memory locations to 1Ptr and 2 Ptr
    void swap(int *element1Ptr, int *element2Ptr)
    {
        int hold = *element1Ptr;
        *element1Ptr = *element2Ptr;
        *element2Ptr = hold;
    }// end swap function
    

完整的将存储在 字符串数组,一个二维字符数组。年龄将存储在 整数数组。 将数组作为并行数组进行管理。数据输入将从 键盘,将读出全名后跟年龄。数据输入将终止 当数组已满或未输入全名时。使用子程序来 输入数据并将数组传递给子程序,不要使用全局数组。一旦 数据完全输入后,使用另一个子程序将数组打印到屏幕上。 然后使用一个子程序对全名数据进行升序排序。重复使用打印 子程序并将排序后的数据打印到屏幕上。编写另一个子程序 将按年龄排序的数据作为主要排序,将全名作为次要排序。最后 重用打印子例程将数据打印到屏幕上。主程序将调用 数据录入函数,接着是打印函数,名称排序函数,打印 功能,年龄排序功能,最后是打印功能。所有数据将传递给 函数,没有全局数据

**** 更新代码 ************

    #define SIZE 5
    #include <stdio.h>
    #include <string.h>
    #include <stdio.h>


    void input(char fullname[][25], int age[]);
    void output(char fullname[][25], int age[]);
    void bubblesortname(char *fullname[], int *age, SIZE size);
    bubblesortage(char *fullname[], int *age, SIZE size);

    int main(int argc, char *argv[]) 
    {
        char fullname[SIZE][25];
        int age[SIZE];
        char *tmp;


        // promt user for names and ages
        input(fullname, age);
        //output unsorted names and ages
        output(fullname, age);

        bubblesortname(fullname,age,SIZE);

        output(fullname, age);

        //sorts age
        bubbleSortage(fullname,age,SIZE);
        //
        output(fullname, age);


        return 0;
    }

    void input(char fullname[][25], int age[]) 
    {
        int i;
        for (i = 0; i < SIZE; i++) 
        {
            fflush(stdin);
            printf("Enter a full name\n");
            //scanf("%[\^n]\n", fullname[i]);
            fgets (fullname[i],40, stdin);
            printf("Enter the age\n");
            scanf("%d", &age[i]);

        }
    }

    void output(char fullname[][25], int age[]) 
    {
        int i;
        for (i = 0; i < SIZE; i++)
            printf("%s, %d\n", fullname[i], age[i]);
    }//end function

    void bubblesortname(char *fullname[], int *age, SIZE size)
    {
         int temp_age;
          char* temp_name;
          int n;

          for (SIZE pass = 0; pass < size - 1; ++pass) 
          {
            for (SIZE n = 0; n < len - 1; ++n) 
            {
              if (strcmp(fullname[n], fullname[n + 1]) > 0) 
              {
                temp_age = age[n];
                age[n] = age[n + 1];
                age[n + 1] = temp_age;

                temp_name = fullname[n];
                fullname[n] = fullname[n + 1];
                fullname[n + 1] = temp_name;


                 }//end if

            }//end inner for

        }//end for

    }//end function

            bubblesortage(char *fullname[], int *ages, SIZE size) 
            {
                int n;
                int temp_age;
                char* temp_name;
                    for (SIZE pass = 0; pass < size - 1; ++pass) 
                      {
                         for (SIZE n = 0; n < size - 1; ++n) 
                            {
                                 if (age[n] > age[n + 1]) 
                                  {

                                    temp_age = age[n];
                                    age[n] = age[n + 1];
                                    age[n + 1] = temp_age;
                                    temp_name = fullname[n];
                                    fullname[n] = fullname[n + 1];
                                    fullname[n + 1] = temp_name;

                                    }// end inner for

                            }// end outer for


                        }// end function

要对字符串进行排序,请使用 strcmp() 进行比较。

同时对alternate/parallel数组进行排序 所以名字和年龄都按照名字排序:

在排序名称时在冒泡排序算法中执行交换的代码中:

添加代码以交换 alternate/parallel 数组(年龄)中的关联条目

如果冒泡排序使用数组索引而不是指针,这将变得容易得多,因为索引也适用于 alternate/parallel 数组

我会尝试解决您的 3 个子问题:

1.如何成功对字符串数组进行排序?

要对任何内容进行排序,您需要一种比较各个组件的方法。要对字符串进行排序,您需要能够比较两个字符串,在 C 中,您可以通过调用 strcmp() 函数来实现。

#include <string.h>
int strcmp(const char *s1, const char *s2);
int strncmp(const char *s1, const char *s2, size_t n);

Description

The strcmp() function compares the two strings s1 and s2. It returns an integer less than, equal to, or greater than zero if s1 is found, respectively, to be less than, to match, or be greater than s2.

The strncmp() function is similar, except it only compares the first (at most) n bytes of s1 and s2.

Return Value

The strcmp() and strncmp() functions return an integer less than, equal to, or greater than zero if s1 (or the first n bytes thereof) is found, respectively, to be less than, to match, or be greater than s2.

下面是一个代码示例,说明如何在 C:

中比较字符串
#include <stdio.h>
#include <string.h>

int main()
{
    const char* jenna = "Jenna";
    const char* mark  = "Mark";

    // warning: Be careful here because the order of strings matters
    //          and is directly related to the result. If you swap them
    //          the result changes sign (1 becomes -1, -1 becomes 1 and
    //          zero stays zero).
    int comparisonResult = strcmp(jenna, mark)

    if (comparisonResult < 0)
    {
        printf("%s is less than %s\n", jenna, mark);
    }
    else if (comparisonResult > 0)
    {
        printf("%s is greater than %s\n", jenna, mark);
    }
    else // We know that (comparisonResult == 0)
    {
        printf("%s is the same as %s\n", jenna, mark);
    }

有了这个,您应该能够修改现有的年龄排序算法以对字符串进行排序。 Here's an example I found on Google.

2。如何让相应的字符串保持适当的年龄?

要在 C 中将不同的数据放在一起,您可以使用 struct。因此,如果您想将姓名和年龄放在一起,您可以按照以下方式创建数据结构:

struct Person {
    char* name;
    int   age;
};

int main()
{
    // The person is a datastructure containing two elements in it.
    struct Person person = { "Mark", 25 };

    // You can access each of the subcomponents of person by using the . operator like in this printf statement.
    printf("Hi, my name is %s and I'm %d years old\n", person.name, person.age);

    return 0;
}

现在每次都必须在 Person 前面输入 struct 很烦人,所以大多数人只是像这样使用 typedef

typedef struct Person_s {
    char* name;
    int age;
} Person;

int main()
{
    Person person = { "Mark", 25 };

    printf("Hi, my name is %s and I'm %d years old\n", person.name, person.age);

    return 0;
}

3。如何打印排序后的字符串而不同时对年龄和字符串进行排序?

同时部分有歧义,你的意思是你不想改变输入的原始顺序吗?

无论如何,你有几个选择。您可以制作所有输入的副本,然后按年龄或姓名对副本进行排序,然后打印副本。或者您可以在打印原始数据后对其进行排序,因为您已经打印了它,所以它的顺序对您来说不再重要。

注意:我试图让你自己解决这个问题,而不是仅仅为你编写代码。我很确定这是您正在研究的某种类型的 assignment/homework,您的用户名表明您是 C 的新手...

加分:

我在第二部分的解释中使用的 typedef 语法我使用了这个例子:

typedef struct Person_s {
    char* name;
    int age;
} Person;

此语法用于表示我要创建一个名为 struct Person_s 的类型,这是它在大括号 { ... definition ... } 内的定义,但请将类型重命名为 struct Person_sPerson(这是最后的部分)。

也许使用 typedef 的不同示例会有所帮助:

typedef int number_type; // make an alias for int and call it number_type

// From here on, we can use number_type instead of int.

number_type main()
{
    number_type number = 7;

    printf("%d\n", number);

    return 0;
}

我们之前对 struct Person_s 做了同样的事情:

typedef 
// Define the struct
struct Person_s {
    char* name;
    int age;
}
// Give it the following alias so that you can save me some typing...
Person;

注意:这是一种简化,试图让初学者清楚,我在掩饰一些事情......对我放轻松!

显然,您需要并行管理数组。根据我原来的回答,使用结构会好得多。

但你不能。所以,你必须有两个数组。原理还是一样的,只是有点乱。使用strcmp比较名字字符串,手动比较年龄。

现在,从技术上讲,您的规范要求两个排序子例程。这意味着您将有一个用于 ages 的数组,它对 int 的数组进行排序,另一个用于 names,它对 char*.

的数组进行排序

整数排序(请注意,这遵循您的排序算法,实际上不是 bubble sort):

void bubble_sort_age(int *arr, size_t len) {
  int temp;
  for (size_t pass = 0; pass < len - 1; ++pass) {
    for (size_t n = 0; n < len - 1; ++n) {
      if (arr[n] > arr[n + 1]) {
        // write a swap function if you really want to
        temp = arr[n];
        arr[n] = arr[n + 1];
        arr[n + 1] = temp;
      }
    }
  }
}

请注意,我对数组索引计数器使用 size_t 类型,因为它保证对任何数组都足够大。

就个人而言,我可能会使用 unsigned int 类型来表示年龄,因为年龄为负值的人没有多大意义。

同样的事情,但是在字符串上使用 strcmp

void bubble_sort_name(char *arr[], size_t len) {
  char* temp;
  for (size_t pass = 0; pass < len - 1; ++pass) {
    for (size_t n = 0; n < len - 1; ++n) {
      if (strcmp(arr[n], arr[n + 1]) > 0) {
        temp = arr[n];
        arr[n] = arr[n + 1];
        arr[n + 1] = temp;
      }
    }
  }
} 

这还不够,因为我们需要确保在排序时将姓名和年龄对保持在一起...所以我们传入 both每当我们排序和交换数组时,我们都会将交换应用于... 两个数组。

现在,如果我们把它们放在一起,它看起来像这样:

// swap BOTH name and age to keep the arrays in sync =)
void bubble_sort_name(char *names[], int *ages, size_t len) {
  int temp_age;
  char* temp_name;
  for (size_t pass = 0; pass < len - 1; ++pass) {
    for (size_t n = 0; n < len - 1; ++n) {
      if (strcmp(names[n], names[n + 1]) > 0) {
        temp_age = ages[n];
        ages[n] = ages[n + 1];
        ages[n + 1] = temp_age;

        temp_name = names[n];
        names[n] = names[n + 1];
        names[n + 1] = temp_name;
      }
    }
  }
}

void bubble_sort_age(char *names[], int *ages, size_t len) {
  int temp_age;
  char* temp_name;
  for (size_t pass = 0; pass < len - 1; ++pass) {
    for (size_t n = 0; n < len - 1; ++n) {
      if (ages[n] > ages[n + 1]) {
        // write a swap function if you really want to
        temp_age = ages[n];
        ages[n] = ages[n + 1];
        ages[n + 1] = temp_age;

        temp_name = names[n];
        names[n] = names[n + 1];
        names[n + 1] = temp_name;
      }
    }
  }
}

void print(char *names[], const int *ages, size_t len) {
  for (size_t n = 0; n < len; ++n) {
    printf("%s %d\n", names[n], ages[n]);
  }
}

int main(void) {
  // Input &c omitted.
  // If you don't know how to malloc/realloc and read input,
  // there should be plenty of other SO questions showing how

  int ages[N_ITEMS] = { -10, 2, -1, -10, 0xDEADBEEF };
  char *names[] = { "one", "two", "-1", "onf", "foo" };

  print(names, ages, N_ITEMS);
  printf("\n");

  bubble_sort_name(names, ages, N_ITEMS);
  print(names, ages, N_ITEMS);
  printf("\n");

  bubble_sort_age(names, ages, N_ITEMS);
  print(names, ages, N_ITEMS);

  return 0;
}

由于您需要按姓名排序,打印,然后主要按年龄排序但次要按年龄排序,我们可以利用冒泡排序的功能。

它是一个stable sort,所以当我们根据不同的标准对数组求助时,一个相等的元素(在新的排序顺序下)将保持相同的顺序(相对于彼此)旧排序将它们分类。

这意味着我们第二次可以简单地按年龄排序,只要我们记得名字和年龄都必须重新排列,这就是我们需要做的:)


专家额外内容:您实际上可以重写冒泡排序方法,以便您可以对字符串和 int 重用它。您可以使用 void * 和强制转换来做到这一点。不过,使用结构类型会好得多。