简体   繁体   中英

Why doesn't this C++ insertion sort work?

I'm learning C++ and this is one of my first programs that is going to sort a list of numbers, I found the algorithm in Kenneth H. Rosen book and wrote it in C++. when I check it on the paper it seems to be correct, but in practice it has some error. For example I enter 3(enter)2(enter)1(enter)4(enter)5(enter) and it returns 3 1 1 4 5 as the answer. I don't know what is the problem, please help.

int main()
{
    int i, j, s, n, k, a[50];
    cout << "Enter number of numbers:\n";
    cin >> n;
    cout << "Enter the numbers:\n";
    for (i = 0; i < n; i++) {
        cin >> a[i];
    }
    for (j = 2; j < n; j++) {
        i = 1;
        while (a[j] > a[i]) {
            i = i + 1; // Here we find the proper place to(if needed) directly insert our number into the sorted part.
        }
        s = a[j];
        for (k = 0; k < j - i - 1; k++) {
            a[j - k] = a[j - k - 1];
        }
        a[i] = s;
    }
    for (i = 0; i < n; i++) {
        cout << a[i] << " ";
    }
    _getch();
    return 0;
}

I've also included the header files and namespace, not written here though. And in the case you think I have used so many variables, sorry about that, I needed them :)

Your index i should start from the first element which is 0 instead of 1.

Fixing line 11 should do the job:

for (j = 2; j < n; j++) {
    i = 0;
    while (a[j] > a[i]) {

Edit: Oh, and also, your variable j should start from the second element which is index 1 instead of 2:

for (j = 1; j < n; j++) {

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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