Insertion sort output

nclude
using namespace std;

int main()
{
int n;
cin>>n;
int arr[100];
int j;
int i;

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

for (int i = 1; i < n; ++i)
{
	int picked=arr[i];
	for (int j = i-1; j >= 0 ; --j)
	{
		if (arr[j]>picked)
		{
			arr[j+1]=arr[j];
		}
	}
	arr[j+1]= picked;
}
for (int i = 0; i < n; ++i)
{
	cout<<arr[i]<<" ";
}
return 0;

}
what is the mistake?

hi @srivastavaayush1611_3fd51b257da0b834
corrected code–>

#include <iostream>
using namespace std;
int main()
{
    int n;
    cin>>n;
    int arr[100];
    int j;
    int i;

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

    for (int i = 1; i < n; i++)
    {
        int picked=arr[i];
        int j;
        for (j = i-1; j >= 0; j--)
        {
            if (arr[j]>picked)
            {
                arr[j+1]=arr[j];
            }
            else{
                break;
            }
        }
        arr[j+1]= picked;
    }
    for (int i = 0; i < n; ++i)
    {
        cout<<arr[i]<<" ";
    }
    return 0;
}
1 Like

I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.

On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.