简体   繁体   English

使用插入排序C ++

[英]Using insertion sort c++

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;
}

In print and getInput your variable i is not initialized to 0 printgetInput您的变量i未初始化为0

You should initialize your i to 0 您应该将i初始化为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. 另外,您应该使用cont var初始化数组大小。 For more details 更多细节

const int n = 7;
 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. 这是您的函数,在其中您尚未初始化i的值。 Initialize i =0; 初始化i = 0; Make it: 做了:

 for(int i = 0; i<n; i++)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM