排序方法的问题(C)

排序方法的问题(C),c,arrays,sorting,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 a

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

我已经运行了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);
}
错误1:
replaced=值[n-1]
您在问题陈述中的示例是:

int test[] = {3,5,2,5,6,100,4,46};
sort(test, 8);
然后您将看到
test[8]
,这是一种未定义的行为

错误2:
replacedhash
replacedhash
如果数组的第一个元素是最大值,则将取消初始化,并且当第一个元素是最大值时,它在以后的循环中可能会有不正确的值

我的想法: 在我看来,你把代码复杂化了。您可能应该在具有最大值的数组中找到索引,然后进行交换。这会更简单

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);
}
void排序(int值[],int n){
做{
//查找最大值的索引
int max=0;

对于(int i=0;i1)应
替换=值[n-1];如果
(max
为false@sharth;嗯,我没有注意到。注释掉的“测试”与我一直在写的测试不同,因此值[8]这不是问题的一部分。我非常欣赏精简版,它更有意义。FWIW:
while(n>1)
而不是
do…while(n!=0)
保存了一个无用的通行证(并处理
n<1
的愚蠢案例!)另外:
int i=1
以避免一次无意义的比较。并且:如果
值[n-1]
实际上是最大值,则可以避免交换,方法是在
for
循环中进行一次比较,并在跳过交换的
if
中进行最终比较。
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);
}