Thread: bubble sort, ordering by a primary variable, then when the same, a secondary variable

  1. #1
    Registered User
    Join Date
    Apr 2017
    Posts
    80

    bubble sort, ordering by a primary variable, then when the same, a secondary variable

    Bit of a lazy question, can't even think about it right now, been a long day. How to make the well known bubble sort algorithm work/sort for two different types of variables? So say you've got a struct with a variable a. That's the primary variable to sort by. But then where all the a values, whatever they are, it doesn't matter, are the same, then these structs should be sorted by a secondary variable, b.

    Here's a copy and paste of the bubble sort algorithm:

    Code:
     for (c = 0 ; c < ( n - 1 ); c++)  {
        for (d = 0 ; d < n - c - 1; d++)
        {
          if (array[d] > array[d+1])
          {
            swap       = array[d];
            array[d]   = array[d+1];
            array[d+1] = swap;
          }
        }
      }

  2. #2
    Programming Wraith GReaper's Avatar
    Join Date
    Apr 2009
    Location
    Greece
    Posts
    2,738
    Let's take your line that does the comparison:
    Code:
    array[d] > array[d+1]
    and convert it to a function since you said these would actually be structs:
    Code:
    compare(&array[d], &array[d+1]) > 0
    Inside that function, you should implement the correct way to compare those two elements so that member "a" takes precedence over member "b", like this:
    Code:
    int compare(const myStruct* e1, const myStruct* e2)
    {
        // if e1->a > e2->a, return 1
        // if e1->a < e2->a, return -1
    
        // if e1->b > e2->b, return 1
        // if e1->b < e2->b, return -1
    
        // Return 0 to signal "equality"    
    }
    Devoted my life to programming...

  3. #3
    Registered User
    Join Date
    Apr 2017
    Posts
    80
    Yup, that makes a lot of sense. Last night, when I really wasn't thinking straight, and hadn't given it much thought either, I was thinking further for loops might be required to cover the extra comparisons, but that didn't seem right, and it wasn't. I'll give your suggestion a go, sure it'll work. Thanks.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 1
    Last Post: 08-12-2011, 03:07 AM
  2. Replies: 7
    Last Post: 04-16-2011, 12:28 PM
  3. Replies: 8
    Last Post: 02-14-2010, 04:14 PM
  4. Replies: 2
    Last Post: 01-17-2009, 10:48 PM
  5. Variable is not a structure and Sort char **
    By ChazWest in forum C Programming
    Replies: 1
    Last Post: 03-08-2002, 09:40 AM

Tags for this Thread