How to sort a table of arrays

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • 123scope
    New Member
    • Mar 2010
    • 12

    How to sort a table of arrays

    Hi readers, I can sort a single array, using the bubble sort method, but I can't sort, the elements of another array.

    eg
    array1[]={4, 3, 7, 5, 1, 5, 8, 7}
    array2[]=[23, 67, 98, 56, 56, 67, 77, 78]

    If i sort array1[] i get

    my array1 = 1, 3, 4, 5, 5, 7, 7, 8
    but my
    array2 = 23, 67, 98, 56, 56, 67, 77, 78

    how do i swap the elements of array2 so it prints corresponding to the array1 which is sorted.
  • Banfa
    Recognized Expert Expert
    • Feb 2006
    • 9067

    #2
    So you have 2 arrays and you want then to maintain their corresponding orders?

    Actually the easiest method is to not keep 2 arrays of related data as separate objects but to put the values into a single object and sort an array of those objects. Such an object exists it is a structure

    Code:
    struct Data {
        int value1;
        int value2;
    };
    Sort an array of these structures by value1 and the value2 will automatically follow the same ordering.

    That is the best solution but if for some reason you can't do that then while sorting array1 everytime you perform a swap on array1 perform the same swap on array2 without actually doing any comparisons on array2.

    Comment

    • 123scope
      New Member
      • Mar 2010
      • 12

      #3
      awesome thanks

      Comment

      • 123scope
        New Member
        • Mar 2010
        • 12

        #4
        yes I have all ready tried the same sort of swap with array2 but, somehow it prints the first element for all the elements for array1.
        eg:

        array1[]= 1, 3, 4, 5, 5, 7, 7, 8
        array2[]= 56, 56, 56, 56, 56, 56, 56, 56

        and the compiler complains invalid operands for the struct data function.

        Comment

        • sridhard2406
          New Member
          • Dec 2007
          • 52

          #5
          You can append the table, when you are doing sorting, please try it, let us know, you are able to do that.

          Comment

          • Banfa
            Recognized Expert Expert
            • Feb 2006
            • 9067

            #6
            I would say that you had not done your swaps on array2 correctly.

            If you change to using a structure you will need to change the types that you use through your sort algorithm.

            It is hard to say much more without seeing code.

            Comment

            Working...