将元素插入数组 C [英] Insert element into array C
问题描述
我有一个之前已排序的数字数组,因此无需对其进行排序,我需要在数组中的有效位置插入一个给定的值,命名为 val
.
I have an array of numbers that has been sorted in before, so there's no need to sort it, I need to insert an given value, named it val
, at a valid position in my array.
我的程序适用于小于最后一个的给定值,但对于该值大于最后一个的情况,我的程序只是不想插入该值.
My program works for a given value that is smaller than the last one, but for the case where the value is bigger than the last one, my program just doesn't want to insert the value.
例如,对于数组 {1, 2, 3, 4, 6}
和值 5
,数组应该是 {1, 2, 3, 4, 5, 6}
,但是对于值 7
我的数组看起来像 {1, 2, 7, 4, 6, 0}
.
For example, for the array {1, 2, 3, 4, 6}
and the value 5
, the array should be {1, 2, 3, 4, 5, 6}
, but for the value 7
my array is looking like {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;
}
推荐答案
你有几个错误:
- 您传递的是
int
而不是int *
,因此您无法更新数组大小 - 您没有正确地将值放入数组中
- You are passing
int
instead ofint *
so you're not able to update array size - You are not correctly placing value in the array
你的代码应该是这样的:
This is how your code should look like:
#include <stdio.h>
void insert(int val, int *nPtr, int v[]);
void display(int n, int v[]);
int main(void) {
int v[10] = {12, 23, 34, 41, 69, 71, 81, 91, 100};
int n;
n = 9;
insert(101, &n, v);
display(n, v);
return 0;
}
void insert(int val, int *nPtr, int v[]) {
int n = *nPtr;
int i, j;
int k = 0;
for (i = 0; i < n + 1; i++)
if (!k) {
if (v[i] > val || i == n) {
for (j = n - 1; j >= i; j--) {
v[j + 1] = v[j];
}
v[i] = val;
n++;
k = 1;
}
}
*nPtr = n;
}
void display(int n, int v[]) {
int i;
for (i = 0; i < n; i++)
printf("%d ", v[i]);
printf("
");
}
您也可以尝试在开头插入数字,例如0
,它仍然可以工作.
You can also try to insert number on the beginning, for example 0
and it will still work.
这篇关于将元素插入数组 C的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!