英文:
Trying to organize an array of structs in C
问题
I'm a relatively new programmer working with structs for the first time in C. Currently I'm tasked with organizing an array of structs based on an int contained within the struct. I have the merge sort algorithm implemented and working with an array of ints, but I am confused on how to sort the ints when they're within a struct.
So far I've tried making an array containing only the ints I'm concerned with. However, then the original array of structs isn't sorted, just the new integer array.
英文:
I'm a relatively new programmer working with structs for the first time in C. Currently I'm tasked with organizing an array of structs based on an int contained within the struct. I have the merge sort algorithm implemented and working with an array of ints, but I am confused on how to sort the ints when they're within a struct.
So far I've tried making an array containing only the ints I'm concerned with. However, then the original array of struts isn't sorted, just the new integer array.
答案1
得分: 0
我假设你的结构看起来像这样,你有一个结构体数组
typedef struct {
int value;
} MyStruct;
MyStruct arr[] = {
{10}, {7}, {8}, {5}, {2}
};
将你的排序算法应用于arr[]
,其中数组中的每个数字可以通过arr[i].value
访问,因此你可以使用这些数字来对数组进行排序。
英文:
I am assuming your struct looks like this and you have an array of the struct
typedef struct {
int value;
} MyStruct;
MyStruct arr[] = {
{10}, {7}, {8}, {5}, {2}
};
apply your sorting algorithm to arr[] where the each number in the array can be accessed by arr[i].value so you can use the numbers to sort the array
答案2
得分: 0
尽管没有明确提问,我猜测你的问题是'对包含结构的数组进行排序,其中结构中的一个整数是关键'。并且结构中还有其他'内容',但不是关键。
如果是这样,你应该对整个结构进行排序,而不仅仅是关键部分。
这里是一个示例:
typedef struct
{
int key;
int other_value;
} ele;
#define SIZE 5
ele arr[SIZE];
void example_bubble_sort(void)
{
int i;
int j;
for (i = 0; i < SIZE; i++)
{
for (j = 0; j < (SIZE - i - 1); j++)
{
if (arr[j].key > arr[j + 1].key)
{
ele temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
return;
}
英文:
Though not asked in a clear way, I guess your question is 'sorting an array of structures, with an int in the structure as the key'.
And there are other 'contents' in the structure but not the key.
If so, you should sort the struct instead of only the key.
Here is an example:
typedef struct
{
int key;
int other_value;
}ele;
#define SIZE 5
ele arr[SIZE];
void example_bubble_sort(void)
{
int i; int j;
for(i=0;i<SIZE;i++)
{
for(j=0;j<(SIZE-i - 1);j++)
{
if(arr[j].key > arr[j+1].key)
{
ele temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
}
return;
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论