Ok the bubblesort for age works. The part I am having trouble with now is the bubblesort for the fullname which needs to happen first. I thought about temporarily storing the sorted ages in an array but I guess that's cheating. I need to data entry, print unsorted name and age, sort name, print sorted name unsorted age, sort age, and print sorted name and age...
好吧,泡泡糖适合年龄。我现在遇到麻烦的部分是要先出现全称的bubblesort。我想暂时将排序后的年龄存储在一个数组中,但我猜这是作弊。我需要数据输入,打印未排序的名称和年龄,排序名称,打印已排序的名称和年龄,打印已排序的名称和年龄……
How can I?
我怎么能呢?
- Sort an array of strings successfully?
- 是否成功排序了字符串数组?
- Keep the appropriate ages with the corresponding strings?
- 用相应的字符串保持适当的年龄?
-
Print the sorted strings without sorting the ages and strings at the same time?
打印已排序的字符串而不同时对年龄和字符串进行排序?
#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
The full will be stored in an array of strings, a two dimensioned array of characters. The ages will be stored in an array of integers. Manage the arrays as parallel arrays. Data entry will be from the keyboard and will read the full name followed by the age. Data entry will terminate when the arrays are full or when nothing is entered for the full name. Use a subroutine to enter the data and pass the arrays to the subroutine, do not use global arrays. Once the data is completely entered, use another subroutine to print out the arrays to the screen. Then use a subroutine to sort the data on the full names, ascending order. Reuse the print subroutine and print the sorted data out to the screen. Write another subroutine which sorts the data on age as the primary sort and full name as the secondary sort. Finally reuse the print subroutine to print the data to the screen. The main program will call the data entry function, followed by the print function, the name sort function, the print function, the age sort function and finally the print function. All data will be passed to the functions, no global data
全部将存储在一个字符串数组中,一个二维字符数组。年龄将存储在一个整数数组中。将数组管理为并行数组。数据输入将来自键盘,并将读取全名和年龄。当数组已满或没有为全名输入任何内容时,数据条目将终止。使用子例程输入数据并将数组传递给子例程,不要使用全局数组。数据完全输入后,使用另一个子例程将数组打印到屏幕上。然后使用子例程对完整名称、升序排序的数据进行排序。重用打印子例程并将已排序的数据打印到屏幕上。编写另一个子例程,将年龄数据排序为主排序,将全名排序为副排序。最后,重用print子例程将数据打印到屏幕上。主程序将调用数据输入函数,然后是打印函数,名称排序函数,打印函数,年龄排序函数,最后是打印函数。所有数据将被传递给函数,没有全局数据
**** UPDATED CODE ************
* * * *更新代码* * * * * * * * * * * *
#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
3 个解决方案
#1
2
You're required to manage the arrays in parallel, apparently. It would be much better to use a struct, as per my original answer.
显然,您需要并行地管理数组。按照我最初的回答,使用结构体会更好。
But you can't. So, you have to have two arrays. The principles are still the same, it's just a bit messier. Use strcmp
to compare name strings, and compare the ages manually.
但是你不能。你必须有两个数组。原则还是一样的,只是有点混乱。使用strcmp比较名称字符串,并手动比较年龄。
Now, technically your specification asks for two sorting subroutines. This means you'll have one for ages, which sorts an array of int
, and another for names, which sorts an array of char*
.
现在,您的规范要求两个排序子例程。这意味着您将拥有一个for age,它对int数组进行排序,另一个for names,它对char*数组进行排序。
Sorting integers (note that this follows your sorting algorithm, which isn't actually a 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;
}
}
}
}
Note that I'm using the size_t
type for array index counters because it is guaranteed to be large enough for any array.
请注意,我正在使用size_t类型的数组索引计数器,因为它保证足够大,可以用于任何数组。
Personally, I would probably use an unsigned int
type to represent age, since a person with a negative age doesn't make much sense.
就我个人而言,我可能会使用一个没有符号的int类型来表示年龄,因为一个人的年龄是负的,没有多大意义。
And here's the same thing, but using strcmp
on strings:
这是一样的,但是在字符串中使用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;
}
}
}
}
This isn't quite enough, because we need to ensure that the pairs of names and ages are kept together when we're sorting... so we pass in both arrays whenever we sort, and whenever we swap, we apply the swap to... both arrays.
这还不够,因为我们需要确保当我们排序的时候,这些名称和年龄是保持在一起的。所以我们每次排序时都传递这两个数组,每次交换时,我们将交换应用到。两个数组。
Now, if we put it all together, it will look something like this:
现在,如果我们把它们放在一起,它会是这样的:
// 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;
}
Since you are required to sort on name, print, and then primary sort on age but secondary sort on age, we can take advantage of a feature of bubblesort.
由于需要对名称、打印进行排序,然后对年龄进行主排序,但对年龄进行次排序,因此我们可以利用bubblesort的特性。
It is a stable sort, so when we resort an array on a different criterion, an elements that are equal (under the new sort order) will be kept in the same order (relative to each other) that the old sort sorted them in.
它是一种稳定的排序,所以当我们在不同的条件下使用数组时,相等的元素(在新的排序顺序下)将保持原来排序的相同顺序(相对于彼此)。
This means we can simply sort on age the second time, and so long as we remember that name and age both have to be rearranged, that's all we need to do :)
这意味着我们可以简单地对第二次排序的年龄进行排序,只要我们记住名字和年龄都必须重新排列,这就是我们要做的:
Extra for experts: you can actually rewrite the bubble sort method so that you can reuse it for both strings and int
. You can do that using void *
and casts. It would be much better to use a struct type, though.
专家额外提示:您可以重写bubble sort方法,以便对字符串和int都可以重用它。不过,最好使用struct类型。
#2
2
I will try and address your 3 sub-questions:
我会尽量回答你的三个问题:
1. How do I Sort an array of strings successfully?
1。如何成功排序字符串数组?
To sort anything you need a way of comparing the individual components. To sort strings you need to be able to compare two strings and in C you do this by calling the strcmp()
function.
要对任何东西进行排序,您需要一种方法来比较各个组件。要对字符串进行排序,您需要能够比较两个字符串,在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 stringss1
ands2
. It returns an integer less than, equal to, or greater than zero ifs1
is found, respectively, to be less than, to match, or be greater thans2
.函数的作用是:比较两个字符串s1和s2。如果发现s1分别小于、等于或大于零,则返回一个小于、等于或大于零的整数,以匹配或大于s2。
The
strncmp()
function is similar, except it only compares the first (at most)n
bytes ofs1
ands2
.strncmp()函数是类似的,除了它只比较s1和s2的第一个(最多)n个字节。
Return Value
返回值
The
strcmp()
andstrncmp()
functions return an integer less than, equal to, or greater than zero ifs1
(or the firstn
bytes thereof) is found, respectively, to be less than, to match, or be greater thans2
.strcmp()和strncmp()函数返回一个小于、等于或大于零的整数,如果发现s1(或其前n个字节)分别小于、匹配或大于s2。
So here's a code example that illustrates how you compare strings in C:
这里有一个代码示例,演示了如何在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);
}
With this you should be able to modify your existing algorithm for sorting ages to sort strings. Here's an example I found on Google.
有了这个,您应该能够修改现有的算法来对字符串进行排序。这是我在谷歌上找到的一个例子。
2. How do I keep the appropriate ages with the corresponding strings?
2。如何保持适当的年龄与相应的字符串?
To keep different data together in C you use a struct
. So if you wanted to keep a name and age together you would make a datastructure along the lines of this:
要在C语言中保持不同的数据,您需要使用结构体。因此,如果你想要保持一个名字和年龄,你可以根据这条线建立一个数据结构:
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;
}
Now it gets annoying having to type struct
in front of Person
every time so most people just use typedef
like this:
每次都要在别人面前输入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. How do I print the sorted strings without sorting the ages and strings at the same time?
3所示。如何打印已排序的字符串而不同时对年龄和字符串进行排序?
The at the same time part is ambiguous, do you mean that you don't want to change the original ordering of your inputs?
同时部分是模糊的,你的意思是你不想改变输入的原始顺序?
In any case you have a couple options. You can either make a copy of all of your inputs and then sort the copy, by either age or name and then print the copy. Or you can sort your original data after you have printed it and its ordering no longer matters to you since you've already printed it.
无论如何你有几个选择。你可以复制你所有的输入,然后根据年龄或名字对拷贝进行排序,然后打印拷贝。或者您可以在打印完原始数据后对其进行排序,它的顺序对您不再重要,因为您已经打印了它。
Note: I'm trying to enable you to solve this problem yourself instead of just writing the code for you. I'm pretty sure this is some type of assignment/homework that you're working on and your username suggests you're new to C...
注意:我试图让您自己解决这个问题,而不是仅仅为您编写代码。我很确定这是你正在做的作业/作业,你的用户名表明你是新手…
For extra points:
加分:
The typedef
syntax I used in the explanation for the 2nd part I used this example:
我在解释第二部分时使用的typedef语法使用了这个示例:
typedef struct Person_s {
char* name;
int age;
} Person;
This syntax is used to say that I want to create a type called struct Person_s
and here is its definition inside of the curly braces { ... definition ... }
but please rename the type from struct Person_s
to Person
(which is the part at the end).
这个语法用来表示我想创建一个名为struct Person_s的类型,这里是它在大括号{…定义……但是请将类型从struct Person_s重命名为Person(这是最后的部分)。
Perhaps a different example of how to use typedef
will help:
也许另一个使用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;
}
We did the same with the struct Person_s
earlier:
我们之前对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;
Note: This is a simplification in an attempt to make it clear for a beginner, I'm glossing over some things... Go easy on me SO!
注意:这是一种简化,试图让初学者明白,我正在粉饰一些事情……别对我太苛刻!
#3
1
To sort strings, use strcmp() to make the comparisons.
要对字符串进行排序,可以使用strcmp()来进行比较。
to also sort the alternate/parallel array, at the same time so names and ages are all sorted according to the name:
也要对交替/并行数组进行排序,同时根据名称对名称和年龄进行排序:
in the code that performs the swap in the bubble sort algorithm when sorting the names:
在冒泡排序算法中执行交换的代码中对名称进行排序:
add code to also swap the associated entries in the alternate/parallel array (the ages)
添加代码也可以交换备用/并行数组中的相关条目(年龄)
this will be made much easier if the bubble sort uses array indexing rather than pointers, as the indexes would also work in the alternate/parallel array
如果气泡排序使用数组索引而不是指针,那么这将变得更加容易,因为索引也可以在备用/并行数组中工作
#1
2
You're required to manage the arrays in parallel, apparently. It would be much better to use a struct, as per my original answer.
显然,您需要并行地管理数组。按照我最初的回答,使用结构体会更好。
But you can't. So, you have to have two arrays. The principles are still the same, it's just a bit messier. Use strcmp
to compare name strings, and compare the ages manually.
但是你不能。你必须有两个数组。原则还是一样的,只是有点混乱。使用strcmp比较名称字符串,并手动比较年龄。
Now, technically your specification asks for two sorting subroutines. This means you'll have one for ages, which sorts an array of int
, and another for names, which sorts an array of char*
.
现在,您的规范要求两个排序子例程。这意味着您将拥有一个for age,它对int数组进行排序,另一个for names,它对char*数组进行排序。
Sorting integers (note that this follows your sorting algorithm, which isn't actually a 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;
}
}
}
}
Note that I'm using the size_t
type for array index counters because it is guaranteed to be large enough for any array.
请注意,我正在使用size_t类型的数组索引计数器,因为它保证足够大,可以用于任何数组。
Personally, I would probably use an unsigned int
type to represent age, since a person with a negative age doesn't make much sense.
就我个人而言,我可能会使用一个没有符号的int类型来表示年龄,因为一个人的年龄是负的,没有多大意义。
And here's the same thing, but using strcmp
on strings:
这是一样的,但是在字符串中使用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;
}
}
}
}
This isn't quite enough, because we need to ensure that the pairs of names and ages are kept together when we're sorting... so we pass in both arrays whenever we sort, and whenever we swap, we apply the swap to... both arrays.
这还不够,因为我们需要确保当我们排序的时候,这些名称和年龄是保持在一起的。所以我们每次排序时都传递这两个数组,每次交换时,我们将交换应用到。两个数组。
Now, if we put it all together, it will look something like this:
现在,如果我们把它们放在一起,它会是这样的:
// 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;
}
Since you are required to sort on name, print, and then primary sort on age but secondary sort on age, we can take advantage of a feature of bubblesort.
由于需要对名称、打印进行排序,然后对年龄进行主排序,但对年龄进行次排序,因此我们可以利用bubblesort的特性。
It is a stable sort, so when we resort an array on a different criterion, an elements that are equal (under the new sort order) will be kept in the same order (relative to each other) that the old sort sorted them in.
它是一种稳定的排序,所以当我们在不同的条件下使用数组时,相等的元素(在新的排序顺序下)将保持原来排序的相同顺序(相对于彼此)。
This means we can simply sort on age the second time, and so long as we remember that name and age both have to be rearranged, that's all we need to do :)
这意味着我们可以简单地对第二次排序的年龄进行排序,只要我们记住名字和年龄都必须重新排列,这就是我们要做的:
Extra for experts: you can actually rewrite the bubble sort method so that you can reuse it for both strings and int
. You can do that using void *
and casts. It would be much better to use a struct type, though.
专家额外提示:您可以重写bubble sort方法,以便对字符串和int都可以重用它。不过,最好使用struct类型。
#2
2
I will try and address your 3 sub-questions:
我会尽量回答你的三个问题:
1. How do I Sort an array of strings successfully?
1。如何成功排序字符串数组?
To sort anything you need a way of comparing the individual components. To sort strings you need to be able to compare two strings and in C you do this by calling the strcmp()
function.
要对任何东西进行排序,您需要一种方法来比较各个组件。要对字符串进行排序,您需要能够比较两个字符串,在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 stringss1
ands2
. It returns an integer less than, equal to, or greater than zero ifs1
is found, respectively, to be less than, to match, or be greater thans2
.函数的作用是:比较两个字符串s1和s2。如果发现s1分别小于、等于或大于零,则返回一个小于、等于或大于零的整数,以匹配或大于s2。
The
strncmp()
function is similar, except it only compares the first (at most)n
bytes ofs1
ands2
.strncmp()函数是类似的,除了它只比较s1和s2的第一个(最多)n个字节。
Return Value
返回值
The
strcmp()
andstrncmp()
functions return an integer less than, equal to, or greater than zero ifs1
(or the firstn
bytes thereof) is found, respectively, to be less than, to match, or be greater thans2
.strcmp()和strncmp()函数返回一个小于、等于或大于零的整数,如果发现s1(或其前n个字节)分别小于、匹配或大于s2。
So here's a code example that illustrates how you compare strings in C:
这里有一个代码示例,演示了如何在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);
}
With this you should be able to modify your existing algorithm for sorting ages to sort strings. Here's an example I found on Google.
有了这个,您应该能够修改现有的算法来对字符串进行排序。这是我在谷歌上找到的一个例子。
2. How do I keep the appropriate ages with the corresponding strings?
2。如何保持适当的年龄与相应的字符串?
To keep different data together in C you use a struct
. So if you wanted to keep a name and age together you would make a datastructure along the lines of this:
要在C语言中保持不同的数据,您需要使用结构体。因此,如果你想要保持一个名字和年龄,你可以根据这条线建立一个数据结构:
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;
}
Now it gets annoying having to type struct
in front of Person
every time so most people just use typedef
like this:
每次都要在别人面前输入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. How do I print the sorted strings without sorting the ages and strings at the same time?
3所示。如何打印已排序的字符串而不同时对年龄和字符串进行排序?
The at the same time part is ambiguous, do you mean that you don't want to change the original ordering of your inputs?
同时部分是模糊的,你的意思是你不想改变输入的原始顺序?
In any case you have a couple options. You can either make a copy of all of your inputs and then sort the copy, by either age or name and then print the copy. Or you can sort your original data after you have printed it and its ordering no longer matters to you since you've already printed it.
无论如何你有几个选择。你可以复制你所有的输入,然后根据年龄或名字对拷贝进行排序,然后打印拷贝。或者您可以在打印完原始数据后对其进行排序,它的顺序对您不再重要,因为您已经打印了它。
Note: I'm trying to enable you to solve this problem yourself instead of just writing the code for you. I'm pretty sure this is some type of assignment/homework that you're working on and your username suggests you're new to C...
注意:我试图让您自己解决这个问题,而不是仅仅为您编写代码。我很确定这是你正在做的作业/作业,你的用户名表明你是新手…
For extra points:
加分:
The typedef
syntax I used in the explanation for the 2nd part I used this example:
我在解释第二部分时使用的typedef语法使用了这个示例:
typedef struct Person_s {
char* name;
int age;
} Person;
This syntax is used to say that I want to create a type called struct Person_s
and here is its definition inside of the curly braces { ... definition ... }
but please rename the type from struct Person_s
to Person
(which is the part at the end).
这个语法用来表示我想创建一个名为struct Person_s的类型,这里是它在大括号{…定义……但是请将类型从struct Person_s重命名为Person(这是最后的部分)。
Perhaps a different example of how to use typedef
will help:
也许另一个使用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;
}
We did the same with the struct Person_s
earlier:
我们之前对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;
Note: This is a simplification in an attempt to make it clear for a beginner, I'm glossing over some things... Go easy on me SO!
注意:这是一种简化,试图让初学者明白,我正在粉饰一些事情……别对我太苛刻!
#3
1
To sort strings, use strcmp() to make the comparisons.
要对字符串进行排序,可以使用strcmp()来进行比较。
to also sort the alternate/parallel array, at the same time so names and ages are all sorted according to the name:
也要对交替/并行数组进行排序,同时根据名称对名称和年龄进行排序:
in the code that performs the swap in the bubble sort algorithm when sorting the names:
在冒泡排序算法中执行交换的代码中对名称进行排序:
add code to also swap the associated entries in the alternate/parallel array (the ages)
添加代码也可以交换备用/并行数组中的相关条目(年龄)
this will be made much easier if the bubble sort uses array indexing rather than pointers, as the indexes would also work in the alternate/parallel array
如果气泡排序使用数组索引而不是指针,那么这将变得更加容易,因为索引也可以在备用/并行数组中工作