Reputation: 3
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;
}
Upvotes: 0
Views: 618
Reputation: 331
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++)
Upvotes: 0
Reputation: 8066
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;
Upvotes: 1