Facing difficulties in shifting & insert new numbers in array
Oct 14, 2012 at 4:48pm UTC
The question says
Write a function named insertNewElement that takes four parameters: an array of integers (List), an integer (newItem), the number of elements in the array (Length), and the maximum size of the array (Max_Size). Assume that the elements in the array are sorted in ascending order. The function should add newItem in a way that the element in the array will remain sorted. Note that the Length of the array should not exceed Max_Size, i.e. if List is full, then the insertion is not performed and an appropriate message is displayed.
My solution but it's wrong
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
void insertNewElement(int List[], int newItem, int &length, const int Max_Size)
{
int index=0;
if (length == Max_Size)
cout<<"Cannot add a new item as the array is full" <<endl;
else
for (int i=0; i<Max_Size-1 && i<length; i++)
{
if (List[i] < newItem)
continue ;
else if (List[i] > newItem)
{
index=i;
for (int x=length; x>index; x--)
{
List[x+1]=List[x];
}
List[index]=newItem;
length++;
}
}
cout<<"The numbers of the array is:\n" ;
for (int j=0; j<=length; j++)
{
cout<<List[j]<<endl;
}
}
Can anybody tell me where is my error exactly, and what should I do?
Oct 14, 2012 at 5:13pm UTC
It is obvious that this loop is invalid
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
for (int i=0; i<Max_Size-1 && i<length; i++)
{
if (List[i] < newItem)
continue ;
else if (List[i] > newItem)
{
index=i;
for (int x=length; x>index; x--)
{
List[x+1]=List[x];
}
List[index]=newItem;
length++;
}
}
You shall not insert the new element inside the loop and change the length of the array.
Last edited on Oct 14, 2012 at 5:14pm UTC
Oct 14, 2012 at 8:40pm UTC
Thanks you, I got it working so far but I don't know weather it is 100% right or still missing things?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
void insertNewElement(int List[], int newItem, int &length, const int Max_Size)
{
int index;
if (length == Max_Size)
cout<<"Cannot add a new item as the array is full" <<endl;
else
{
for (index=0; index<length; index++)
if (List[index]>newItem)
break ;
for (int i=length; i>index; i--)
List[i]=List[i-1];
List[index]=newItem;
length++;
cout<<"The numbers of the array is:\n" ;
for (int j=0; j<Max_Size; j++)
{
cout<<List[j]<<endl;
}
}
}
Topic archived. No new replies allowed.