Search code examples
cbubble-sort

Reversed bublesort keeping index of positions?


I have two tables in C of size 8 with the following elements

int  arr1[8]  = {400, 100, 213, 876, 900, 564, 211, 230};
float arr2[8] = {5.5, 2.1, 9.4, 2.6, 7.5, 4.3, 1.1, 7.5};

I want to make a program to display data based on arr2 values descending (using bublesort) as below :

ARR1  ARR2
213   9.4
900   7.5
230   7.5
400   5.5
564   4.3
876   2.6
100   2.1
211   1.1

-

#include <stdio.h>

void swap(float *xp, float *yp) 
{ 
    float temp = *xp; 
    *xp = *yp; 
    *yp = temp; 
} 

void BubbleSort(float arr[], int n) 
{ 
   int i, j; 
   for (i = 0; i < n-1; i++){   

       for (j = 0; j < n-i-1; j++) {

           if (arr[j] < arr[j+1]) 
              swap(&arr[j], &arr[j+1]); 
       }
   }
}

 void main(){
    int  arr1[8]  = {400, 100, 213, 876, 900, 564, 211, 230};
    float arr2[8] = {5.5, 2.1, 9.4, 2.6, 7.5, 4.3, 1.1, 7.5}; 

 }

The problem I have is that I understand that I need to keep index of rows. Could you help me please ?


Solution

  • This looks a bit like some homework, so I will not show a complete program.

    You have two options:

    1. Create an additional index array with index values 0..7 for your data arrays and sort by swapping the index array values. Something like
      if (arr[index[j]] < arr[index[j+1]]) swap(&index[j], &index[j+1]);

    2. Pass both arrays arr1 and arr2 to BubbleSort and swap the values with the same index pair for both arrays. Something like
      if (arr2[j] < arr2[j+1]) { swapInt(&arr1[j], &arr1[j+1]); swapFloat(&arr2[j], &arr2[j+1]); }

    Better than using two arrays that are linked by the index (similar to a structure of arrays) use an array of structures.

    struct data {
        int intval;
        float floatval;
    };
    
    struct data arr[8];
    

    and in BubbleSort something like

    if (arr[j].floatval < arr[j+1].floatval)
        swap(&arr[j], &arr[j+1]);