Reputation: 53
I'm trying to sort a array of struct. But i want sort by one the elements. For example I'm sorting with bubble sort.
struct example{
int num;
char str[5];
} ex[90];
for(int i = 0; i < 88; i++){
for(int o = 0; o < 88; o++){
if(ex[o].num > ex[o + 1].num){
swap(ex[o].num, ex[o + 1].num);
}
}
}
In this code how can i change ex[o].num as ex[o].str without writing code again?
Upvotes: 1
Views: 38
Reputation: 1922
One could implement comparison functions and use the standard library's qsort
. It's hard to beat the standard library for general sorting except if you want a stable sort. qsort
takes in a compar
,
The compar argument is a pointer to the comparison function, which is called with two arguments that point to the elements being compared. The application shall ensure that the function returns an integer less than, equal to, or greater than 0, if the first argument is considered respectively less than, equal to, or greater than the second.
Like such,
#include <stdlib.h> /* EXIT_* qsort */
#include <stdio.h> /* printf */
#include <string.h> /* strcmp */
#include <assert.h>
struct Example {
int num;
char str[5];
} ex[90];
static const size_t ex_size = sizeof ex / sizeof *ex;
static void fill(struct Example *const example) {
assert(example);
example->num = rand() / (RAND_MAX / 100.0);
example->str[0] = rand() / (RAND_MAX / 26.0) + 'A';
example->str[1] = rand() / (RAND_MAX / 26.0) + 'a';
example->str[2] = rand() / (RAND_MAX / 26.0) + 'a';
example->str[3] = rand() / (RAND_MAX / 26.0) + 'a';
example->str[4] = '\0';
}
static void print(const struct Example *const example) {
assert(example);
printf("%d\t\"%s\"\n", example->num, example->str);
}
/* Implements <Example>Comparator. */
static int comp_num(const void *va, const void *vb) {
const struct Example *a = va, *b = vb;
return (a->num > b->num) - (a->num < b->num);
}
/* Implements <Example>Comparator. */
static int comp_str(const void *va, const void *vb) {
const struct Example *a = va, *b = vb;
return strcmp(a->str, b->str);
}
int main(void) {
size_t i;
for(i = 0; i < ex_size; i++) fill(&ex[i]);
for(i = 0; i < ex_size; i++) print(&ex[i]);
printf("Sorting by num.\n");
qsort(ex, ex_size, sizeof *ex, &comp_num);
for(i = 0; i < ex_size; i++) print(&ex[i]);
printf("Sorting by str.\n");
qsort(ex, ex_size, sizeof *ex, &comp_str);
for(i = 0; i < ex_size; i++) print(&ex[i]);
return EXIT_SUCCESS;
}
Upvotes: 0