gpt4 book ai didi

c - 我的插入排序的实现正确吗?

转载 作者:行者123 更新时间:2023-11-30 18:49:43 25 4
gpt4 key购买 nike

这是我关于堆栈溢出的第一个问题。我刚刚通过 CS50 开始了我的编程世界之旅。我的 C 插入排序代码与讲师的伪代码建议的稍有不同。我只是想知道以下代码是否正确以及如何改进?非常感谢。

int arr[6] = {23, 42, 4, 16, 8, 15};

for (int i = 1; i < 6; i++) // Iterating over the unsorted portion of array.
{
int element = arr[i]; // This is the first element of the unsorted portion.
int temp = -1;
for(int j = i-1; j >= 0 && element < arr[j]; j--) // Iterating over the unsorted portion of array from right to left.
{
arr[j+1] = arr[j];
temp = j;
}

if(temp != -1) // If temp does not change, the element is already sorted.
{
arr[temp] = element;
}
}

最佳答案

恭喜,您的代码确实有效。

看到这一点的第一种方法是将此代码放入函数中,例如 main(),并在运行算法后按顺序打印每个元素。如果结果不是你所期望的,那么它肯定不起作用,但反之则不然。但是,如果您通过了第一次尝试,您应该开始针对其他情况(尤其是极端情况)测试您的代码。

这里另一个有用的选项是使用 GDB,这是一个调试器,可以在代码执行的每一步显示整个数组,尤其是在 CS50 IDE 上实现的调试器,这实际上非常令人赏心悦目。

此外,HackerRank 的 challengesinsertion sort可能会帮助你学习这个。除此之外,祝你的类(class)顺利,希望你喜欢!

关于c - 我的插入排序的实现正确吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42044056/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com