Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

First element of array not showing

I was coding a function that squares every number and then sort the array in ascending order
But When I ran my code it is not showing the first element of the array
i.e. if the array is [1 2 3 4 5]

It is showing only [ 4 9 16 25 ]
Code:

#include <bits/stdc++.h>
#include<vector>
using namespace std;

void sortedSquaredArray(vector<int> &v){

    vector<int> ans;

    int leftPtr = 0;
    int rightPtr = v.size()-1;
    while(leftPtr < rightPtr){
        if(abs(v[leftPtr]) < abs(v[rightPtr])){
            ans.push_back(v[rightPtr] * v[rightPtr]);
            rightPtr--;
        }
        else{
            ans.push_back(v[leftPtr] * v[leftPtr]);
            leftPtr++;
        }
    }

    reverse(ans.begin(),ans.end());

    cout<<"Sorted Squared Array: [ ";
    for(int i=0; i<ans.size(); i++){
        cout<<ans[i]<<" ";
    }
    cout<<"]"<<endl;

}

int main(){

    // ? Given an integer array 'a' sorted in non-decreasing order, return an array of squares of each number sorted in non-decreasing order

    int n; cin>>n;

    vector<int> v;

    for(int i=0; i<n; i++){
        int ele; cin>>ele;
        v.push_back(ele);
    }

    sortedSquaredArray(v);
    
    return 0;
}

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

You are missing an equals sign in your "while" inside sortedSquaredArray function. It should look like this: while(leftPtr <= rightPtr).

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading