Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to implement swapping of structs for the insertion sorting algorithm in C

I have a working insertion sort algorithm that sorts integers stored in an array. In a different program I have created a struct with words and a count. I need to sort structs stored in an array alphabetically using the same insertion sort. I understand how to compare them, however I cannot find a way to swap them. Ideas?

typedef struct { char * word; int count; } wordType;
like image 748
Busch Avatar asked Feb 16 '23 16:02

Busch


1 Answers

You can swap structs the same way that you swap integers:

wordType tmp;
wordType a = {.word="hello", .count=5};
wordType b = {.word="world", .count=11};
tmp = a;
a = b;
b = tmp;

Demo on ideone.

like image 83
Sergey Kalinichenko Avatar answered Apr 05 '23 23:04

Sergey Kalinichenko