c - 我必须使用 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” .
解决方案
首先,交换是不正确的,你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;
}
现在它应该可以工作了。
推荐阅读
- numpy - input reshape problem about using tf.layers.conv3d
- reactjs - 在画布上进行文本处理后提取图像数据url,并在Material-UI的CardMedia中显示结果
- vuejs2 - 事件和自引用组件 vue.js
- c - 在不运行合成器的情况下使用 x11 协议获取覆盖窗口需要什么?
- google-apps-script - 编写用于删除工作表数据创建的日历项目的代码
- vba - 根据 Access 中的多个条件返回子表单值
- php - 从 foreach 循环中获取唯一值时面临问题
- tensorflow - 如何在张量流中打印出预测值
- java - 谁可以进行此 JPQL 查询?
- android - 系统应用程序在供应商分区中读取/写入数据