i want to sort an array, why is this logic wrong.

#include

using namespace std;

int main()

{

int n,temp=0;

cin>>n;

int arr[n];

cout<<"enter inputs:: ";

for(int i=1;i<=n; i++)

{

    cin>>arr[i];

}

for (int i = 0; i < n; i++)

{

    if(arr[i]>arr[i+1])

    {

        arr[i]=temp;

        arr[i]=arr[i+1];

        temp=arr[i+1];

    }

}



for (int i = 0; i < n-1; i++)

{

    cout<<arr[i]<<" ";

}

return 0;

}

I can see you have done some beginners errors in the code.

for(int i=1;i<=n; i++){
    cin>>arr[i];
}

While taking input you have initialized with i=1, but the array indexing starts from arr[0] till arr[n-1], so your arr[0] will always have no value assigned, and you are also trying to access arr[n] element which is out of bound given the array size is n, it can result in undefined behaviour.

for (int i = 0; i < n; i++){
    if(arr[i]>arr[i+1]){
        arr[i]=temp;
        arr[i]=arr[i+1];
        temp=arr[i+1];
    }
}

In this part of your code correct implementation of sorting is not done, also swapping of elements is also not done in the right way.

I would suggest you to once go through sorting topic again and then implement the code.

This article might help: https://www.freecodecamp.org/news/sorting-algorithms-explained-with-examples-in-python-java-and-c/