反向 bublesort 保持头寸索引?

Reversed bublesort keeping index of positions?

我在 C 中有两个大小为 8 的表,其中包含以下元素

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};

我想制作一个程序来显示基于 arr2 值降序的数据(使用 bublesort) 如下:

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}; 

 }

我的问题是我知道我需要保留索引 的行。 请问你能帮帮我吗 ?

这看起来有点像作业,所以我不会展示完整的程序。

您有两个选择:

  1. 为您的数据数组创建一个索引值为 0..7 的附加索引数组,并通过交换索引数组值进行排序。像
    if (arr[index[j]] < arr[index[j+1]]) swap(&index[j], &index[j+1]);

  2. 将数组 arr1arr2 都传递给 BubbleSort,并用相同的索引对交换两个数组的值。像
    if (arr2[j] < arr2[j+1]) { swapInt(&arr1[j], &arr1[j+1]); swapFloat(&arr2[j], &arr2[j+1]); }

比使用由索引链接的两个数组(类似于数组结构)更好的是使用结构数组。

struct data {
    int intval;
    float floatval;
};

struct data arr[8];

BubbleSort中类似

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