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;
}
7
  • 4
    Hello, welcome to StackOverflow! Have you trying debugging through your code step-by-step to see where the issue is? Commented Jan 21, 2015 at 19:51
  • Related: You may find this implementation a bit more brief. Commented Jan 21, 2015 at 19:53
  • @JohnOdom Yeah, and it compiles fine it's just not doing what it's supposed to do. Commented Jan 21, 2015 at 19:54
  • 3
    @gymnastm117 He never said it didn't compile. Debugging it would have shown the unexpected value of i in the print loop. Pretty sure that was his point. Commented Jan 21, 2015 at 19:55
  • int a[n] should throw an error. You cannot initialize arrays in c++ with a variable size. You would need to make n a const variable. const int n = 7; int a[n]; Commented Jan 21, 2015 at 19:55

2 Answers 2

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;
Sign up to request clarification or add additional context in comments.

2 Comments

Oh right thank you, I can't believe I missed that! But it still isn't asking for user input.
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.
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++)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.