反向泡沫排序保持仓位指数?

问题描述 投票:0回答:1

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

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

 }

我遇到的问题是我明白我需要保留行的索引。请问你能帮帮我吗 ?

c bubble-sort
1个回答
1
投票

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

您有两种选择:

  1. 为数据数组创建索引值为0..7的附加索引数组,并通过交换索引数组值进行排序。就像是 if (arr[index[j]] < arr[index[j+1]]) swap(&index[j], &index[j+1]);
  2. 将两个数组qazxsw poi和qazxsw poi传递给冒泡排序,并将这些值与两个数组的相同索引对交换。就像是 arr1

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

arr2

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];
© www.soinside.com 2019 - 2024. All rights reserved.