Sorting names and IDs

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • toefraz
    New Member
    • Nov 2007
    • 19

    Sorting names and IDs

    Hey, guys. I've been using a selection sort for sorting 1d arrays, but now i've got a 2d array with names and ids.

    Code:
    string employee[name][id]
    and i can't figure out how to change the algorithm to sort just the names and have the ids still attached to them such as:

    Code:
    Smith, John 12
    Q, Suzie 47
    Ford, Henry 22
    yields

    Code:
    Ford, Henry 22
    Q, Suzie 47
    Smith, John 12
    any help would be much appreciated.
  • Ganon11
    Recognized Expert Specialist
    • Oct 2006
    • 3651

    #2
    What are you sorting by; names, or IDs?

    Basically, where you swap values, you'll have to swap the name values as well as the id values, which will involve re-writing your swap function.

    Comment

    • toefraz
      New Member
      • Nov 2007
      • 19

      #3
      I'm sorting by names. I think I'll just use strcat to put the name and id into one string and just sort using a 1d algorithm then split them apart.

      Or do you think another way would be easier/more efficient?

      Comment

      • Ganon11
        Recognized Expert Specialist
        • Oct 2006
        • 3651

        #4
        That will certainly work, but the suggestion I gave will also work, and will avoid any messy string work. What sorting function are you using? Whatever it is, when it swaps two values, you'll just rewrite that part to swap both the name and ID values. It's not hard - probably involving maybe 2 or 3 more lines of code at the most.

        Comment

        • weaknessforcats
          Recognized Expert Expert
          • Mar 2007
          • 9214

          #5
          Originally posted by toefraz
          I'm sorting by names. I think I'll just use strcat to put the name and id into one string and just sort using a 1d algorithm then split them apart.
          You sort variables. Your variables contain names plus an ID. That means your variables are struct variables. That means you have a 1D array of struct variables. That means you swap struct variables based on a comprare of the names inside the variables.

          "Putting things together and later taking them apart" is a poor design approach.

          Try to keep every thing in terms of a single variable. Then you can write functions to swap variables, to assign one to another, to copy, to assign, etc.

          Comment

          Working...