I'm trying to make a function to insert a few integers into a sorted vector and display the integers in decreasing order. Actually is from my college tutorial question. Not that i don't want to ask my lecturer but i'm trying to learn myself how to solve the problem and the question stated not to make any changes in the main function.Below is the code.

#include <iostream>
#include <vector>

using namespace std;

void insertInDecreasingOrder(vector<int>& v, int n)
{
    // My code here
	for(int i = n; i >= 0; i--)
	{
		v.push_back(i);
	}
}

//Do not change the main function
int main()
{
    vector<int> v;
    v.push_back(200);
    v.push_back(100);
    v.push_back(50);
    v.push_back(25);
    v.push_back(10);

    int numOfElements = 0;
    cout << "Enter number of elements: ";
    cin >> numOfElements;

    int n = 0;
    cout << "Enter integers: ";
    for(int i=0; i<numOfElements; i++)
    {
        cin >> n;
        insertInDecreasingOrder(v, n);
    }

    cout << "Decreasing order: " << endl;
    for(int i=0; i<v.size(); i++)
    {
        cout << v[i] << " ";
    }
    cout << endl;


    return 0;
}

My question is how to make my program to able to display the series of integer in decreasing order like the sample output below.

Sample output :
=============
Enter number of elements: 4
Enter integers: 5 205 25 75
Decreasing order:
205 200 100 75 50 25 25 10 5

By the look of main(), insertInDecreasingOrder() is meant to insert a single value into it's sorted position. So there are two steps:

  1. Find the sorted position of the value
  2. Insert the value

Since the vector is assumed to be sorted coming into the function, you can just search from the beginning until v[i] is less than n ; that's your sorted position. Then insert n there and you're done.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.