C-反向Bublesort保留位置索引



我有两个尺寸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]);

最新更新