如何同步两个数组

时间:2013-12-03 23:45:11

标签: c++ arrays sorting

我有2个相同大小的数组,它们具有我需要同步的单独类型。一个数组是我按降序排序的双精度列表。另一个是字符33-90的列表,它们对应于它们各自的ASCII值。在对双打列表进行排序之前,2个阵列排列良好,但我不能以相同的方式对字符列表进行排序。我需要发生的是要同步的位置,EX:y[i] = ch[i];但该命令不起作用。

void sortChars(int x[], double y[])
{
    int i;
    int largestIndex;
    int location;
    double temp;
    char ch[58];

    for (int i = 0; i < 58; i++)
        ch[i] = 33 + i;

    for (i = 0; i < 58; i++)
    {
        //Step a
        largestIndex = i;
        for (location = i + 1; location < 58; location++)
            if (x[location] > x[largestIndex])
                largestIndex = location;
            //Step b
        temp = x[largestIndex];
        x[largestIndex] = x[i];
        x[i] = temp;
    }

    for (i = 0; i < 58; i++)
    {
        //Step a
        largestIndex = i;
        for (location = i + 1; location < 58; location++)
            if (y[location] > y[largestIndex])
                largestIndex = location;
            //Step b
        temp = y[largestIndex];
        y[largestIndex] = y[i];
        y[i] = temp;
    }

    for (int i = 0; i < 58; i++)
    {
        cout << ch[i] << " times used: " << left << setw(20) << x[i];
        cout << fixed << showpoint << setprecision(6);
        cout << '\t' << "% of file: " << y[i] << endl;
    }
}

我已尝试设置ch[i] = y[i],我尝试使用y[]中的选择排序,并将步骤y中的所有b部分更改为ch。你将如何匹配这两个阵列?请尽量不要使用std::类型命令,因为我的所有项目都使用using namespace std;

1 个答案:

答案 0 :(得分:0)

看起来你的意思是在第一个for循环中嵌套第二个和第三个for循环。像这样:

for (int i = 0; i < 58; i++)
{
    ch[i] = 33 + i;

  for (i = 0; i < 58; i++)
  {
    //Step a
    largestIndex = i;
    for (location = i + 1; location < 58; location++)
        if (x[location] > x[largestIndex])
            largestIndex = location;
        //Step b
    temp = x[largestIndex];
    x[largestIndex] = x[i];
    x[i] = temp;
  }

  for (i = 0; i < 58; i++)
  {
    //Step a
    largestIndex = i;
    for (location = i + 1; location < 58; location++)
        if (y[location] > y[largestIndex])
            largestIndex = location;
        //Step b
    temp = y[largestIndex];
    y[largestIndex] = y[i];
    y[i] = temp;
  }

  for (int i = 0; i < 58; i++)
  {
    cout << ch[i] << " times used: " << left << setw(20) << x[i];
    cout << fixed << showpoint << setprecision(6);
    cout << '\t' << "% of file: " << y[i] << endl;
  }
}