Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

C++ sort by insertion proplem

  1. Jul 30, 2015 #1
    hi Guys
    i wrote a insertion sort code which is
    Code (C):
    #include <iostream> /*Waver*/
    using namespace std;
    int main()

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

    cout<<"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++)
    cout<<a[i] <<"  ";
    return 0;
    }
     
    it work fine with some size used in array and wont work with other size
    i mean when i enter n=5 it work fine when i enter n=4 it wont work and sort is wrong

    when n=5

    fy3fnp.jpg


    and when n=4
    the sort is wrong and error appear with last number
    s5l6jl.jpg

    i just want to know what i did wrong . thanks in advance
     
  2. jcsd
  3. Jul 30, 2015 #2
    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.
     
  4. Jul 30, 2015 #3

    jedishrfu

    Staff: Mentor

    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.
     
  5. Jul 30, 2015 #4
    the debugger didnt cought any thing 14vc6h.jpg
     
  6. Jul 30, 2015 #5

    rcgldr

    User Avatar
    Homework Helper

    Change the second (or the third) for loop to use < instead of <=. You're indexing beyond the end of the array.
     
  7. Jul 31, 2015 #6

    jedishrfu

    Staff: Mentor

    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.
     
Know someone interested in this topic? Share this thread via Reddit, Google+, Twitter, or Facebook