Home > Software engineering >  First element of array not showing
First element of array not showing

Time:12-01

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;
}

CodePudding user response:

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

  • Related