0

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];
  }
2
Contributors
2
Replies
4
Views
9 Years
Discussion Span
Last Post by tracethepath
1

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.

Votes + Comments
thanx...it worked
This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.