Given a sorted vector V and an element a, put the element a into the vector keeping the vector sorted.
Example:
INPUT
[3 24 88]
55
OUTPUT
[3 24 55 88]
EDIT: the way I wrote the code means that I expect that it is given a sorted vector of elements(so a vector that starts from the little one to the bigger one).
#include <iostream>
usingnamespace std;
int main () {
//Initialization:
constint N = 100;
int vec[N];
int number = 0, numbvec = 0, n = 0, temp = 0;
//Input:
cout<<"How many elements do you want to put in the vector?\n";
cin>>n;
for (int i = 0; i<n; i++) {
cin>>numbvec;
vec[i] = numbvec;
}
cout<<"Insert another element.\n";
cin>>number;
//Procedure:
for (int j = 0; j<n; j++) {
if (number < vec[j]) {
temp = vec[j];
vec[j] = number;
number = temp;
}
}
//Output:
for (int k = 0; k<n+1; k++) {
cout<<vec[k]<<" ";
}
//Termination:
return 0;
}
The problem is in the second for loop. Because I don't know how to put the last element of the vector in the next position. Any idea how to do that?
I stored it into vector. This is my vector:
int vec[N];
This is an array, not a vector. You can easily use all those functions with arrays instead of vectors (although you will have to manage size manually).
So, you need first to find insertion point, index of elemnt where new value should be.
Then you will need to shift all values from the end to your point one element to the right:
1 2 3 4
int n = /*...*/;//Amount of elements in array
int p = /*...*/; //insertion point
for(int i = n; i > p; --i)
array[i] = array[i-1];
Then you need to insert element to the place it should occupy: array[p] = value;