CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 15 of 25

Threaded View

  1. #18
    Join Date
    Apr 1999
    Posts
    27,449

    Re: Need help writing a bubble sort with no loops

    Quote Originally Posted by kristyy_mariee View Post
    Ok i only just saw the last two replies I did this today its a bit off but i tried.
    Ok this is what ive done so far..
    First, you should pass the array, the size, and the current index. So right at the start, your bubblesort() function doesn't have enough information to know where to start the comparison, and whether to finish or not.
    Code:
    int bubblesort( int arrayf[], int currentItem, int arraySize, bool isSwapped)
    {
      //... stuff missing...
      // somewhere code like this will be made to test the items
      if (arrayf[currentItem] > arrayf[currentItem + 1] ) 
      {
           // stuff to do
      }
      // more stuff to do...
      //...
      // somewhere, a call like this will be made to compare the next two items
      bubblesort( arrayf, currentItem + 1, arraySize, isSwapped );
    }   
    
    int main()
    {
        int arr[] = { 10, 2, 45, 6, 7, 1, -3, 44, 3, 0, 12, 8 };
        const int numValues = sizeof(arr) / sizeof(arr[0]);
    
        bool bSwapped = false;
        bubblesort(arr, 0, numValues, bSwapped);  // start from the first item
    }
    The main() function is complete. There is nothing else to add to get the bubblesort to start. Also note the dummy data, and the way I computed the number of items so that you are not stuck on 15 items.

    The part you need to fill in is the function, and what I described is how you should be proceeding.

    The bubblesort function knows the array, it knows the current item, it knows the array size, and it knows when the items are swapped. So you know everything you need to know as to whether to stop sorting or keep sorting, or go back to the top of the array and start over, etc. I just put in two random lines of code as to a hint of what needs to be done. There is a lot of missing code, for example, checking if you're at the end of the array, you need to decide whether to quit or to go back to the beginning.

    So go through this by hand.

    The first thing you do is determine if currentItem is at the end of the array. If not, then you will be testing items 0 and 1 (10 and 2). They are out of sequence, so you a) swap them and b) set the bSwapped to true c) call bubblesort again to go to the next two items. Etc...

    Regards,

    Paul McKenzie
    Last edited by Paul McKenzie; March 26th, 2012 at 07:27 PM.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured