Share your repls and programming experiences

← Back to all posts
Sort and Search in C
h
LennyPhoenix

Basic example of using the bubble sort and binary search algorithm in C.

Feel free to share any improvements you can think of!

UPDATE: Added Menu and Merge Sort algorithm

Voters
maxina
ANDREWVOSS
Kai_Justice
nro2collaborate
DynamicSquid
LennyPhoenix
Comments
hotnewtop
DynamicSquid

Cool! I noticed something though.

One line 47, you have:

But I don't think that's enough, because the list memory looks like this:

And calling free(list) does this:

But you still have to deallocate the other list elements.

So I think you have to loop through the list and free each element.

LennyPhoenix

@DynamicSquid If you look in list_generate you can see that list is allocated with calloc, meaning you only have to free the head pointer of the array.

If I tried to free each item in the list, like this:

We would get an error, as freeing the original pointer would free the whole list:

The memory of the list actually looks more like this:

DynamicSquid

@LennyPhoenix Oh, interesting. But if you used malloc, then you would have to free each element individually right?

LennyPhoenix

@DynamicSquid In the case of a linked list, then yes, however malloc would also only need you to run free on the head pointer in this case

DynamicSquid

@LennyPhoenix Oh, never knew that. Sorry if these are really dumb questions, I do C++, and I always think these two languages are very similar, but every time I find out that I'm wrong lol

LennyPhoenix

@DynamicSquid Don't worry about it :D
C++ and C might have near identical syntax, but C++ has evolved drastically so many of the features are completely different now (it's no-longer just "C with classes").

DynamicSquid

@LennyPhoenix Yeah, I'm currently coding a lot more in C to try and learn it a lot more. But thanks for the help!

LennyPhoenix

@DynamicSquid No problem, good luck with learning C!

LennyPhoenix