0

I wrote a code for insertion sort and there appears to be no errors (it compiles fine), but it doesn't print anything or ask for a user input. I have looked over this several times and I can't figure out why the code won't run properly. Thanks!

#include <iostream>
using namespace std;

void getInput(int a[ ], int n);
void insertionSort(int a[ ], int n);
void print(int a[ ], int n);

int main()
{
    int n=7;
    int a[n];

    getInput(a, n);
    insertionSort(a, n);
    print(a, n);

    system("pause");
    return 0;
}


void getInput(int a[ ], int n)
{
    for(int i; i<n;i++)
    {
        cout<<"Number? ";
        cin>>a[i];
    }
}

void insertionSort(int a[ ], int n)
{
    int temp, j;
    for(int i = 0; i<n; i++)
    {
        temp = a[i];
        j=i;

        while(j>0 && a[j-1] > temp)
        {
            a[j]= a[j-1];
            j=j-1;
        }
    }
}


void print(int a[ ], int n)
{
    for(int i= 0; i<n; i++)
    {
        cout<<a[i]<<"    ";   
    }

    cout<<endl;
}

2 Answers2

1

In print and getInput your variable i is not initialized to 0

You should initialize your i to 0

for(int i = 0; i<n;i++)
{
    cout<<"Number? ";
    cin>>a[i];
}

Same for the print method.

Also, you should initialize your array size with a cont var. For more details

const int n = 7;
Community
  • 1
  • 1
Jérôme
  • 7,866
  • 4
  • 27
  • 35
  • Oh right thank you, I can't believe I missed that! But it still isn't asking for user input. – gymnastm117 Jan 21 '15 at 19:49
  • 2
    It's a good practice to get used to compiling with -Wall and even -pedantic -Werror. These are errors that a compiler can notify you about and you'll get a better feeling of what is standard behavior. – Tasos Vogiatzoglou Jan 21 '15 at 19:53
0
 void print(int a[ ], int n)
 {
     for(int i; i<n; i++)
 {
    cout<<a[i]<<"    ";   
 }

    cout<<endl;
 }

This is your function, in which you have not initialize the value of i. Initialize i =0; Make it:

 for(int i = 0; i<n; i++)
Prakhar Verma
  • 309
  • 1
  • 2
  • 10