0

hey guyz i was trying to make a program for insertion sort but its not working
please someone help...

#include<iostream>
#include<conio.h>
using namespace std;

main()
{
    int i,m,num[5];
    cout<<"Enter Integer Values";
    for(int a=1;a<=5;a++)
    cin>>num[a];
    for(int j=2;j<=5;j++)
    {
        i=1;
        while(num[i]>num[j])
        i=i+1;
        m=num[j];
      for(int k=0;k<=j-i-1;k++)
      {
        num[j-k]=num[j-k-1];
      }
    num[i]=m;
    cout<<num[i]<<num[j];
    }

getch();
}

please help

2
Contributors
1
Reply
10
Views
4 Years
Discussion Span
Last Post by deceptikon
0

The most greivous error is that arrays in C++ are 0-based and you're treated yours as if it were 1-based. num[5] is not a valid index. Consider this:

#include<iostream>

using namespace std;

int main()
{
    int i,m,num[5];
    cout<<"Enter Integer Values";
    for(int a=0;a<5;a++)
        cin>>num[a];
    for(int j=1;j<5;j++)
    {
        i=1;
        while(num[i]>num[j])
            i=i+1;
        m=num[j];
        for(int k=0;k<=j-i-1;k++)
        {
            num[j-k]=num[j-k-1];
        }
        num[i]=m;
    }

    for (int i = 0; i < 5; i++) {
        cout << num[i] << '\n';
    }
}
This topic has been dead for over six months. 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.