gpt4 book ai didi

c - 插入排序功能不起作用。为什么?

转载 作者:行者123 更新时间:2023-11-30 20:58:03 25 4
gpt4 key购买 nike

void insertionsort(int a[], int n){
int next, i, j;
for(i=1; i<n; i++){
if(a[i]<a[i-1]){
for(j=i-2; j>=0; j--){
if(a[j]<a[i]){
next = a[i];
a[i] = a[j];
a[j] = next;
}
}
}
}
}

这是一个应该按升序对数组元素进行排序的函数。为什么不起作用?

最佳答案

您的解决方案与算法所述不完全一致。您可能会考虑不使用两个嵌套的 for 循环:

void insertionsort(int a[], int n){
int i, key, j;
for (i = 1; i < n; i++)
{
key = a[i];
j = i-1;

/*
Move all elements in the array at index 0 to i-1, that are
greater than the key element, one position to the right
of their current position
*/
while (j >= 0 && a[j] > key)
{
a[j+1] = a[j];
j = j-1;
}
a[j+1] = key;
}
}

关于c - 插入排序功能不起作用。为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54707502/

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