首页 > 解决方案 > 我必须使用 2 种方法将这个数组中的元素从大到小排列,但输出完全不同

问题描述

这是代码

#include <stdio.h>
#include <stdlib.h>
#include <math.h>

int IndexOfMaxInRange(int ra[], int first, int last)
{
    int index = first;
    int max = ra[first];
    for(int i = first+1; i < last; i++)
    {
       if(ra[i] > max)
          {
              index = i;
          }
    }
    return index;
}

void SwapElement(int ra[], int iOne, int iTwo)
{
    int temp = ra[iOne];
    ra[iTwo] = ra[iOne];
    ra[iOne] = temp;
}

void SortArray(int ra[],int length)
{
    for(int i = 0; i < length; i++)
    {
    SwapElement(ra, i, IndexOfMaxInRange(ra, i, (length-1)));
    }
}
int main(void)
{
   int ra[5] = {2,5,8,3,4};
   int length = sizeof (ra) / sizeof (ra[0]);
   SortArray(ra, length);
   for(int i = 0; i < length; i++)
   {
     printf("%d ", ra[i]);
   }
   return(EXIT_SUCCESS);
}

我应该从大到小排列元素,但我的输出是:“2 5 5 2 4” .

标签: csortingmethods

解决方案


首先,交换是不正确的,你ra[iTwo]在这个过程中输了。改成

void SwapElement(int ra[], int iOne, int iTwo)
{
    int temp = ra[iOne];
    ra[iOne] = ra[iTwo];
    ra[iTwo] = temp;
}

第二个错误是您没有更新当前的最大值IndexOfMaxInRange

if(ra[i] > max)
{
    max = ra[i];
    index = i;
}

现在它应该可以工作了。


推荐阅读