我在使用我编写的排序方法时遇到问题。它应该找到最大值,并将数组中的最后一个值替换为最大值(并将该值移动到最后一个值所在的位置)。
我已经运行了 gdb,看起来 if
语句总是在执行,并且出于某种原因 max = values[0]
总是将 max 设置为 0。当然我是 C 的新手,所以我可能对发生的事情有误。
/**
* Sorts array of n values.
*/
void sort(int values[], int n)
{
// TODO: implement an O(n^2) sorting algorithm
int max; //hold the max value through the iteration
int replaced; //to hold the value at the end of the array
int replacedhash; //to hold the location of the max value
do
{
replaced = values[n];
max = values[0]; //reset max to 0 for new iteration
for(int i = 0; i<n ; i++)
{
//check if the next value is larger,
//then update max and replacedhash if it is
if (max < values[i])
{
max = values[i];
replacedhash = i;
}
}
values[replacedhash] = replaced; //next three lines swap the values
n--;
values[n] = max;
} while (n!=0);
}
我会通过运行来使用它:
int main() {
int test[] = {3,5,2,5,6,100,4,46};
sort(test, 8);
printarray(test, 8);
}
最佳答案
错误 1:replaced = values[n-1];
你在问题陈述中的例子是:
int test[] = {3,5,2,5,6,100,4,46};
sort(test, 8);
然后你将查看test[8]
,这是未定义的行为
错误 2:replacedhash
如果数组的第一个元素是最大值,replacedhash
将被取消初始化。当第一个元素是最大值时,它可能在以后的循环中有一个不正确的值。
我的想法:
在我看来,您使代码过于复杂了。您可能应该只在数组中找到具有最大值的 index,然后进行交换。它会更简单。
void sort(int values[], int n) {
do {
// Find index of maximum value
int max = 0;
for(int i=0; i<n; i++)
if (values[max] < values[i])
max = i;
// Swap
int temp = values[max];
values[max] = values[n-1];
values[n-1] = temp;
n--;
} while (n != 0);
}
关于c - 排序方法的问题 (C),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25121854/