#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/
Because if a input is [9, 7, 3, 1, 2]
As per logic of your code it checks 9 and 7 first then swaps it so array become [7, 9, 3, 1, 2]
Then it will check 9 and 3 and swaps it then array looks like [7, 3, 9, 1, 2] and your loop goes on and at last i looks like [7, 3, 1, 2, 9]. you can observe here it is a linear algorithm so once your loop terminates the array[0] will be 7 and array will not be sorted
It would help you a lot if you study more about sorting algorithm especially selection, insertion and bubble sort.
Selection Sort