Why is my insertion sort code not working for certain array sizes?

  • Topic: C/C++ 
  • Thread starter waver.
  • Start date
  • Tags Tags
    C++ Sort
5 replies · 2K views · last reply
waver.
Messages
8
Reaction score
0
hi Guys
i wrote a insertion sort code which is
Code:
#include <iostream> /*Waver*/
using namespace std;
int main()

{
int n,i,m;
float a[100],k;

count<<"enter the amount of number";
cin>>n;

for(i=0; i<n; i++)
cin>>a[i];

for(i=1; i<=n; i++)
{
    for(m=1 ; m<=i; m++)
    {
      if(a[m]<a[m-1])
      {
          k=a[m-1];
          a[m-1]=a[m];
          a[m]=k;
      }

    }
}
for(i=0; i<n; i++)
count<<a[i] <<"  ";
return 0;
}
it work fine with some size used in array and won't work with other size
i mean when i enter n=5 it work fine when i enter n=4 it won't work and sort is wrong

when n=5

Console window showing the prompt 'enter the amount of number', input 5, then the output sequence 2 2 5 6 9 followed by the process return message.
and when n=4
the sort is wrong and error appear with last number
Console window titled with a path to an insertion sort program; output shows entered values 4, 8, 6, 2 and sorted-looking output 4 2 6 6.53221e-039, with a red arrow pointing at the last value.


i just want to know what i did wrong . thanks in advance
 
Hint: You are mixing 0-based and 1-based indexing in your logic. This is not a good idea. Read about off-by-one errors, and go from there.
 
I would use your debugger and step through the code making sure you agree with what values the computer has set. Doing this you should be able to locate your mistake.

If you think that's too difficult then sprinkle print statements after key lines to see values of indexes and other key variables.
 
jedishrfu said:
I would use your debugger and step through the code making sure you agree with what values the computer has set. Doing this you should be able to locate your mistake.

If you think that's too difficult then sprinkle print statements after key lines to see values of indexes and other key variables.

the debugger didnt cought any thing
Screenshot of a debugger console output showing 'Setting breakpoints', 'Debugger name and version: GNU gdb (GDB) 7.5', 'Child process PID: 1616', '[Inferior 1 (process 1616) exited normally]', and 'Debugger finished with status 0', with a status bar showing main.cpp, Line 15, Column 18.
 
Change the second (or the third) for loop to use < instead of <=. You're indexing beyond the end of the array.
 
When I said use the debugger to step through your code, I didn't mean run your code in the debugger.

The debugger can literally step one line at a time and as you do that you can inspect the values of any variable to see if they are what you expect. Many times you will see your error right away.

Or in the case of @rcgldr's hint you will discover that you looped one too many times.