c - 排序方法的问题 (C)

标签 c arrays sorting

我在使用我编写的排序方法时遇到问题。它应该找到最大值,并将数组中的最后一个值替换为最大值(并将该值移动到最后一个值所在的位置)。

我已经运行了 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/

相关文章:

c++ - C 或 C++ - 动态增长/收缩磁盘支持的共享内存

c - 在 glibc 源代码中哪里可以找到 select() 源代码?

javascript - For循环找不到数组的最大值(Javascript)

php - 获取数组中每第 n 个值的平均值

c# - .NET Framework 中是否存在用于比较的现有委托(delegate)?

c - C中重复某个菜单的函数

c++ - 我怎样才能得到一个程序的状态?

c++ - XDR 序列化可变长度字符串数组

python - 使用 list.count 就地使用 .sort() 对列表进行排序不起作用。为什么?

java - 数组中的数据去哪儿了?