Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chris Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Bubble sorting a 2D array by a column.

Status
Not open for further replies.

humanic

Programmer
Oct 15, 2007
3
US
I have a 2D array that I need bubble sorted according to the last column, and I can't seem to get it right. Here's what i have so far:



Code:
int bubble(int twoarray[][4], int limit){
    int temp[4], index;
    for (;limit>0;limit--){
        for (index=0;index<limit;index++){
             for (int i =0;i<4;i++ ){
                 if (twoarray[index][3]>twoarray[index+1][3]){
                 for (i=0;i<4;i++){
                 temp[i]=twoarray[index][i];
                 }
                 for (i=0;i<4;i++){
                 twoarray[index+1][i]=twoarray[index][i];
                 }
                 for (i=0;i<4;i++){
                 twoarray[index+1][i]=temp[i];
                 }

Why is this not working?
 
Think about the last round of i-loops (when i is eq 3) and i+1 indicies in these codes. Probably, you have the same problem with index-loops...

 
Argh! I even worked this out on paper, but it is not sorting!
Code:
int bubble(int twoarray[][4], int total){
    int temp[4];
      for (int index=0;index<total-1;index++ ){
        if (twoarray[index][3]>twoarray[index+1][3]){
           for (int i=0;i<4;i++){
               temp[i]=twoarray[index][i];
               twoarray[index][i]=twoarray[index+1][i];
               twoarray[index+1][i]=temp[i];
           }
        }
      }
 
Well, you have one pass of bubble sorting algorithm.
Only one (largest) element goes into its room.
Invent (outer) loop to proceed sorting (or see your text-book more carefully;)...
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top