Skip to content

Instantly share code, notes, and snippets.

@guilbep
Last active December 31, 2015 05:58
Show Gist options
  • Save guilbep/7944022 to your computer and use it in GitHub Desktop.
Save guilbep/7944022 to your computer and use it in GitHub Desktop.
I made a bubble sort algorithm not very effective just for the purpose of showing how.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
typedef struct list {
struct list* next;
int value;
} s_list;
s_list *newItem(int value){
s_list *my_list;
my_list = (s_list*)malloc(sizeof(s_list));
my_list->value = value;
my_list->next = NULL;
return my_list;
};
s_list *addItemToList(s_list* list, s_list *item)
{
s_list *tempList = list;
if (item == NULL){
item = newItem(0);
}
if (list){
while (tempList->next){
tempList = tempList->next;
}
tempList->next = item;
} else {
list = item;
}
return list;
}
void printList(s_list *list)
{
while (list){
printf("%d\n",list->value);
list = list->next;
}
}
s_list* bubbleSort(s_list *list)
{
s_list* start = list;
s_list* prev;
int swap;
int isSorted = 0;
if (list){
while (list && isSorted == 0){
prev = list;
list = list->next;
// by default we said the list is sorted
isSorted = 1;
while (list){
if (prev->value > list->value)
{
swap = list->value;
list->value = prev->value;
prev->value = swap;
isSorted = 0;
}
prev = list;
list = list->next;
}
list = start;
}
}
return start;
}
int main(int argc, char** argv)
{
s_list *my_list = NULL;
my_list = addItemToList(my_list, newItem(53));
my_list = addItemToList(my_list, newItem(43));
my_list = addItemToList(my_list, newItem(7));
my_list = addItemToList(my_list, newItem(3));
my_list = addItemToList(my_list, newItem(1253));
my_list = addItemToList(my_list, newItem(55444));
printList(my_list);
printf("sort\n\n");
printList(bubbleSort(my_list));
printf("--\n");
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment