gpt4 book ai didi

C - 将数字插入数组并保持排序顺序

转载 作者:行者123 更新时间:2023-11-30 21:23:44 25 4
gpt4 key购买 nike

我正在尝试创建一个能够将整数插入数组并保持其排序顺序的程序。即,每次插入一个数字时,它都会循环遍历数组以查找应插入的位置,将该位置之后的每个元素推到一个索引上以为插入腾出空间,然后插入该值。无论出于何种原因,我似乎都无法解决这个问题。如果有人可以提供任何见解或帮助,我们将不胜感激。

struct data
{
int numbers[10];
int length;
};

void insert(struct data *x, int newNumber);


void insert(struct data *x, int newNumber)
{
int i, k;

if(x->length == 0)
{
x->length++;
x->numbers[0] = newNumber;
}

// Increase Length
x->length = x->length + 1;

// Loop Through the array
for(i = 0; i < x->length; i++)
{
// Find location where newNumber should come after
if(x->numbers[i] < newNumber)
{
// Shift each element until i
for(k = x->length-1; k > i; k--)
{
x->numbers[k+1] = x->numbers[k];
}

// Set next element equal to newNumber
x->numbers[k] = newNumber;
}
}
}

最佳答案

像这样修复

#include <stdio.h>

#define MAX_ELEMENT_LENGTH 10

struct data {
int numbers[MAX_ELEMENT_LENGTH];
int length;
};

void insert(struct data *x, int newNumber){
int i, k;

if(x->length == 0){
x->numbers[x->length++] = newNumber;
} else if(x->length < MAX_ELEMENT_LENGTH){//need this check
//x->length = x->length + 1;//Do not increment before the loop. because x->numbers[i] occurs out of bounds

for(i = 0; i < x->length; i++){ //descending order
if(x->numbers[i] < newNumber){//descending order
//insert position is i
for(k = x->length-1; k >= i; k--){//k > i --> k >= i
x->numbers[k+1] = x->numbers[k];
}
break;//exit loop
}
}
x->numbers[i] = newNumber;
x->length++;
}
}

int main(void){
//DEMO
struct data x = { {0}, 0 };

insert(&x, 5);
for(int i = 1; i < 11; ++i)
insert(&x, i);

for(int i = 0; i < x.length; ++i)
printf("%d ", x.numbers[i]);
puts("");
return 0;
}

关于C - 将数字插入数组并保持排序顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41786547/

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