开始设计
This commit is contained in:
@@ -0,0 +1,45 @@
|
||||
#include "c_SelectionSort.h"
|
||||
#include <stdlib.h>
|
||||
#include <stdio.h>
|
||||
|
||||
typedef struct {
|
||||
char title[50];
|
||||
int pubYear;
|
||||
double price;
|
||||
} Book;
|
||||
|
||||
// Custom comparison function: Sort by publication year ascending
|
||||
int compareBooksByYear(const void* a, const void* b) {
|
||||
const Book* b1 = (const Book*)a;
|
||||
const Book* b2 = (const Book*)b;
|
||||
|
||||
if (b1->pubYear < b2->pubYear) return -1;
|
||||
if (b1->pubYear > b2->pubYear) return 1;
|
||||
return 0;
|
||||
}
|
||||
|
||||
int main() {
|
||||
// Initialize an unsorted library array
|
||||
Book library[] = {
|
||||
{"The C Programming Language", 1978, 42.50},
|
||||
{"Clean Code", 2008, 35.00},
|
||||
{"Introduction to Algorithms", 1990, 85.99},
|
||||
{"Design Patterns", 1994, 54.95}
|
||||
};
|
||||
size_t count = sizeof(library) / sizeof(library[0]);
|
||||
|
||||
printf("Before Sorting:\n");
|
||||
for (size_t i = 0; i < count; i++) {
|
||||
printf("Year: %d | Title: %s\n", library[i].pubYear, library[i].title);
|
||||
}
|
||||
|
||||
// Call generic selection sort
|
||||
c_SelectionSort(library, count, sizeof(Book), compareBooksByYear);
|
||||
|
||||
printf("\nAfter Sorting (By Year Ascending):\n");
|
||||
for (size_t i = 0; i < count; i++) {
|
||||
printf("Year: %d | Title: %s\n", library[i].pubYear, library[i].title);
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
Reference in New Issue
Block a user