I have to sort the linked list by the last name and by the balance. The function has two modes. If the user want to sort by balance then the mode is equal five other wise the mode sorts the function by last name. I used bubble sort but can't figure it out. If someone could help me out i will greatly appreciated it.
This is the function to sort the list based on balance and last name:
The for loops could be useful if you know the number of nodes in the list but you will want to use nested while loops instead.
If you are going to use bubble sort then you may want to start out by writing a function which swaps two adjacent nodes in the list. This function would be called within the sort function.
Your current code has some problems. For one thing, you can't put a while loop directly into a struct. A struct isn't a function! A struct can have member functions, though. Those member functions can have while loops.
Basically, a bubble sort does this:
1) Check if i > i+1.
2a) If yes: swap and restart algorithm.
2b) If not, do i = i+1.
3) Repeat.
Once you can swap two elements, all you need to do is use that repetitively.
Thanks you for ur reply. So i did the sort for the last name i got to compile without any error, but the function doesn't sort the list the list stays the same as before. do i have to pass in the list as a reference.
can someone help me out I can't get this working. I have the code above, it compiles correctly doesn't sort the list. Any suggestion would help. THANKS
What are you trying to do here? if ( strcmp ( (current->member_last,last), (current->next->member_last,last) ) == 1 )
I think you want something more like: if ( strcmp(current->member_last, current->next->member_last) == 1 ).
I recommend (again) that you write and test a swap function separately from the sort function.
As it is, if there is something wrong with both the swap method AND the sort method you may never figure out how to fix them. Divide and conquer!
the following code above work but the only problem i am having is that it keeps deleting the node and not swapping around. i don't know why it keep doing that.
i guess i want to start from the beginning because i can't get the code to work.
so this is the struct function and the function i am reading in the list from into the linked list:
Then you just have to code your own sorting algorithm. There are so many. Quicksort, Bubbeshort, Shellsort etc etc. You need to implement one of them and then fit your linked list into that algorithm to do sorting.
Try looking for Open Source C sorting function. It will cut down your time by a lot!
PS I used to pronounce Shellsort as Self Shocked! :O