Thread: Want to be sure.

  1. #1
    Registered User
    Join Date
    Nov 2005
    Posts
    95

    Want to be sure.

    How hard is it to implent bubble sort on
    a single linked list ?

    By hard I mean, that we will have to write diffrent
    code for each private case. Like if the list contains
    only two juctions and other case if more. A case for dealing with the head . etc.



    Just to be sure that we are talking on the same things
    here is a bubble sort on an array :
    Code:
    void  bubble_sort(int  arr[], int sarr)
    {
    int  i , j;
    
    
    for ( i = 0 ; i < sarr - 1 ; ++i )
        for ( j = sarr-1 ; j > i ; --j )
            if ( arr[j] < arr[j-1] )
               swap(arr+j, arr+j-1);
    }

    By saying "single linked list." Im mean that I have
    only one pointer for the next junction. ( there is no
    prev pointer).

  2. #2
    Lurking whiteflags's Avatar
    Join Date
    Apr 2006
    Location
    United States
    Posts
    9,612
    I think it would be easier to implement something like an insertion sort or shell sort, since in most good single linked list implementations, you have an insert function you can use to properly place values. Both of the sorts I've suggested are stable and faster than bubble sort. Happy searching the web!
    Last edited by whiteflags; 05-13-2006 at 08:01 AM.

  3. #3
    Registered User OnionKnight's Avatar
    Join Date
    Jan 2005
    Posts
    555
    It shouldn't be too hard to implement a bubble sort of singly linked lists. Have a pointer that keeps the previous element of the loop and one that keeps the current element, that way you can compare the current and previous elements like your code did
    if ( arr[j] < arr[j-1] )
    I'm assuming this what troubled you the most. Don't forget to remap what the elements next-pointer points to either.

Popular pages Recent additions subscribe to a feed