i have made a menu driven program for selection sort, bubble sort and insertion sort..
the first two are working correctly but despite writing the correct code (according to me, i have checked my code many times) the insertion sort is not giving the desired output..

here's my piece of code:

int n, arr3[25];
  cin>>n;                                  //size of the array
  cout<<endl;
  for(int i=0; i<n; i++)
  {
    cout<<"Enter element "<<(i+1)<<" : ";
    cin>>arr3[i];
  }
  int temp, j;
  for(i=1; i<=n; i++)
  {
    temp=arr3[i];
    j=i-1;
    while(temp<arr3[j])
    {
      arr3[j+1]=arr3[j];
      j--;
    }
    arr3[j+1]=temp;
  }
  cout<<"\n\nThe Sorted Array Is "<<endl;
  for(i=0; i<n; i++)
  {
    cout<<"\nElement Number "<<(i+1)<<" : "<<arr3[i];
  }

Watch your fencepost conditions. j can become negative.

Try tracing your sort using this input:

arr3 = 1 3 7 2 9 0 5
       j
         i
temp = 3

Good luck.

commented: thanx...it worked +1

thank u sooo much...

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.