CIS课程作业:C语言中用指针排序Dog结构体数组求助
Hey there! Let's work through sorting your struct Dog array for your CIS programming assignment. I'll walk you through two practical approaches—one where we build the sort from scratch (perfect for understanding the basics) and another using C's built-in qsort() function (cleaner and more efficient for real-world use).
First: Let's Finalize the Dog Struct
First, let's fill out the incomplete struct you started. I'll add a name string and a size field (we'll use an integer here, but you could swap it for a float if you're using weight instead of a size category):
#include <stdio.h> #include <stdlib.h> #include <string.h> #define MAX_DOGS 10 // Max 10 dogs as required struct Dog { char name[50]; // Store the dog's name int size; // Example: 1=small, 5=large, or actual weight in kg // Add other fields (age, breed, etc.) if needed for your assignment };
Approach 1: Manual Bubble Sort (Great for Learning)
Bubble sort is simple to implement and easy to follow, which makes it ideal for homework. We'll write two separate functions: one to sort by name, and one to sort by size.
Sort by Dog Name
To sort strings, we use strcmp() (from <string.h>)—it compares two strings lexicographically and returns a negative number if the first string comes before the second, positive if it comes after, and 0 if they're equal.
// Sorts the Dog array by name (ascending dictionary order) void sortDogsByName(struct Dog dogs[], int count) { for (int i = 0; i < count - 1; i++) { for (int j = 0; j < count - i - 1; j++) { // Swap if current dog's name comes after the next one if (strcmp(dogs[j].name, dogs[j+1].name) > 0) { struct Dog temp = dogs[j]; // Temporary struct to hold the swap dogs[j] = dogs[j+1]; dogs[j+1] = temp; } } } }
Sort by Dog Size
Sorting by size is simpler since we're comparing integers—just compare the size fields directly:
// Sorts the Dog array by size (ascending order: smallest to largest) void sortDogsBySize(struct Dog dogs[], int count) { for (int i = 0; i < count - 1; i++) { for (int j = 0; j < count - i - 1; j++) { // Swap if current dog is larger than the next one if (dogs[j].size > dogs[j+1].size) { struct Dog temp = dogs[j]; dogs[j] = dogs[j+1]; dogs[j+1] = temp; } } } }
Approach 2: Using qsort() (Standard Library Method)
C's standard library has a built-in sorting function called qsort() that's more efficient than bubble sort for larger datasets. It requires a custom comparison function that tells it how to compare two struct Dog elements.
Comparison Function for Name Sorting
// Comparison function for qsort() to sort by name int compareByName(const void* a, const void* b) { // Cast the void pointers to Dog pointers const struct Dog* dogA = (const struct Dog*)a; const struct Dog* dogB = (const struct Dog*)b; // Use strcmp to compare names return strcmp(dogA->name, dogB->name); }
Comparison Function for Size Sorting
// Comparison function for qsort() to sort by size int compareBySize(const void* a, const void* b) { const struct Dog* dogA = (const struct Dog*)a; const struct Dog* dogB = (const struct Dog*)b; // Return difference to sort ascending (swap dogB and dogA for descending) return dogA->size - dogB->size; }
Putting It All Together in main()
Here's how you'd use these sorting functions in your main() function:
int main() { struct Dog dogs[MAX_DOGS]; int dogCount = 0; // Example: Populate the array with 3 dogs (replace with your input logic) strcpy(dogs[0].name, "Buddy"); dogs[0].size = 3; strcpy(dogs[1].name, "Max"); dogs[1].size = 5; strcpy(dogs[2].name, "Bella"); dogs[2].size = 2; dogCount = 3; // Option 1: Use bubble sort to sort by name sortDogsByName(dogs, dogCount); printf("Sorted by Name:\n"); for (int i = 0; i < dogCount; i++) { printf("Name: %-10s | Size: %d\n", dogs[i].name, dogs[i].size); } // Option 2: Use qsort to sort by size qsort(dogs, dogCount, sizeof(struct Dog), compareBySize); printf("\nSorted by Size:\n"); for (int i = 0; i < dogCount; i++) { printf("Name: %-10s | Size: %d\n", dogs[i].name, dogs[i].size); } return 0; }
Key Notes to Remember
- Never compare strings with
==: This compares memory addresses, not the actual text. Always usestrcmp()for string comparisons. - Sort order: For ascending order (A-Z, smallest to largest), use the logic above. To sort descending, flip the comparison (e.g.,
strcmp(dogs[j+1].name, dogs[j].name) > 0for bubble sort, ordogB->size - dogA->sizefor qsort). - Array bounds: Make sure
dogCountnever exceedsMAX_DOGS(10) to avoid overflowing your array.
内容的提问来源于stack exchange,提问作者Thomas Brefeld

