列表排序(C)中存在递归问题

问题描述 投票:0回答:1

对于学校,我们正在执行列表排序。我们必须为每个赋值使用此确切的函数结构,将列表的最后一个元素与最大的元素递归交换,直到处理完列表为止。我已经测试了我的解决方案,并且可以解决该问题,直到递归为止,这时它会进行核心转储和退出。

这是我的职能

void selection_sort(int array[], int length){

    if (length <= 0)return;

    int largest = array[0], place_holder, i;

    for(i = 0; i < length; i ++){
        if (array[i] > largest){ //finds the largest number
            largest = array[i];
            place_holder = i; //marks where it was found
        }
    }
    array[place_holder] = array[length - 1];//places n-1th element into space of largest number
    array[length - 1] = largest;//places largest element into n-1th place

    selection_sort(array, length - 1);
}

也许我不完全理解递归。

c recursion
1个回答
0
投票

place_holder可能在array[place_holder]未初始化。像这样初始化它:

    int largest = array[0], place_holder = 0, i; /* add "= 0" */
© www.soinside.com 2019 - 2024. All rights reserved.