gpt4 book ai didi

c - 将数字添加到已排序的降序数组而不扰乱顺序 (C)

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

所以这里我填充数组并进行排序。我需要将从键盘输入的数字插入到数组中,而不需要敲除其顺序。请告诉我我该怎么做。

#include <stdio.h>

int main(void)
{
//Creating array
int a[5];
int i, j, temp;

printf("Enter number to create array\n");
for (i = 0; i < 5; i++)
scanf("%d", &a[i]);

//Sorting the array ascending descending
for (i = 1; i < 5; i++) {
temp = a[i];
for (j = i - 1; j >= 0; j--)
if (temp > a[j]) {
a[j + 1] = a[j];
a[j] = temp;
}
}
//Output of sorted array
for (i = 0; i < 5; i++)
printf("%d\n", a[i]);
return 0;
}

最佳答案

数组的大小一旦定义就固定了。如果要向其中添加元素,则需要定义另一个具有增加的大小的数组。如果您想保持排序顺序,则必须将现有元素与新元素进行比较。

#include <stdio.h>

int main(void)
{
//Creating array
int a[5];
int i, j, temp;
int extra;

printf("Enter number to create array\n");
for (i = 0; i < 5; i++)
scanf("%d", &a[i]);

//Sorting the array ascending descending
for (i = 1; i < 5; i++) {
temp = a[i];
for (j = i - 1; j >= 0; j--)
if (temp > a[j]) {
a[j + 1] = a[j];
a[j] = temp;
}
}

//Output of sorted array
for (i = 0; i < 5; i++)
printf("%d\n", a[i]);

puts("Enter another number to add");
scanf("%d", &extra);

/* Define a larger array to hold the extra element. Naturally, you can
extend this to use a variable value from user input. */
int b[6];
j = 0;
for (i = 0; i < 5; i++) {
if (extra > a[i]) {

/* insert the extra number in the proper order */
b[j++] = extra;
b[j++] = a[i];

/* You have to have a way to stop further comparisons once an
insertion point is reached. In this case, it's a simple
expedient of setting the value to zero. Many times a boolean
flag is used for this purpose. Using zero for this assumes
that you're only sorting positive integers. */
extra = 0;
}
else {

/* otherwise, just copy over the sorted elements */
b[j++] = a[i];
}
}
for (i = 0; i < 6; i++)
printf("%d\n", b[i]);

return 0;
}

如果您使用的是堆分配的整数数组,则可以使用 realloc() 来调整其大小,然后找到插入点,像排序一样使用临时变量,并将其余数组元素向下洗牌 1。

关于c - 将数字添加到已排序的降序数组而不扰乱顺序 (C),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48373016/

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