【发布时间】:2017-11-06 18:17:49
【问题描述】:
我有一个之前已排序的数字数组,因此无需对其进行排序,我需要在我的数组中的有效位置插入一个给定的值,命名为val。
我的程序适用于小于最后一个的给定值,但对于该值大于最后一个的情况,我的程序只是不想插入该值。
例如,对于数组{1, 2, 3, 4, 6} 和值5,数组应该是{1, 2, 3, 4, 5, 6},但对于值7,我的数组看起来像{1, 2, 7, 4, 6, 0}。
#include <stdio.h>
void insert(int val, int *n, int v[])
{
int index;
index = n - 1;
if (n == 0)
{
v[0] = val; // check if array is empty
n = n + 1; // v[0] becomes the given value
} // increase size of array
if (val > v[index])
{
v[index+1] = val; // given value is bigger than the last value in array
n = n + 1; // increase size
}
else
{
while (index >= 0 && v[index] > val)
{
v[index+1] = v[index]; //shift items to the right
index--;
}
v[index + 1] = val; //after moving elements to the right
n = n + 1; // i set the value to the valid position
}
}
void display(int n, int v[])
{
int i;
for (i = 0;i < n; i++)
printf("%d ", v[i]);
}
int main(void)
{
int v[10] = { 12, 23, 34, 41, 69, 71, 81, 91, 100 };
int n;
n = 9; // size of array
insert(101,n,v); // 101 is given value to insert
display(n,v);
return 0;
}
【问题讨论】:
-
为什么
n参数是int*而不是int? -
int *n ... int index = n - 1;会在启用良好的编译器上发出警告。节省时间、避免尴尬并启用警告。 -
在插入到打印数组的显示函数后,我需要将 N 与增加的值一起传递,它确实在我的计算机上显示了警告,但我仍在努力解决指针