插入排序导致程序崩溃

时间:2016-02-26 20:07:58

标签: c++

我正在构建一个程序,用户输入的数字最多为100次,最后输入一个负整数。该程序应该对数字进行排序并将它们显示给用户。现在我的程序在进入排序循环时崩溃,我不知道为什么。

#include <iostream>
using namespace std;

void print(char nums[], int count)
{

    int j;
    for (j = 0; j < count; j++)
        for (j = 0; j < count; j++)
            cout << " " << nums[j];
    cout << endl;
}

void Sort(char nums[], int count)
{
    int i, j, tmp;

    for (i = 1; i < count; i++) {
        j = i;
        while (nums[j - 1] > nums[j]) {
            tmp = nums[j];
            nums[j] = nums[j - 1];
            nums[j - 1] = tmp;
            j--;
        } //end of while loop
        print(nums, count);
    } //end of for loop
}

int main()
{
    char nums[101];
    int count = 0;

    cout << "Please enter between 2 and 100 intgers, ending with a negative                                                    integer.\nThe Negative will not be included in the list;\n";

    for (int count = 0; count <= 100; count++) {
        int temp;
        cin >> temp;
        if (temp < 0) {

            break;
        }
        nums[count] = temp;
        count++;
    }
    nums[count + 1] = '\0';

    Sort(nums, count);
}

1 个答案:

答案 0 :(得分:0)

至少有一个问题是你使用了错误的<?php if(!empty($strategy->assisting)):?> <?php $count = count($strategy->assisting); ?> <ul class="needs-padding"> <?php foreach($strategy->assisting as $k => $asst): ?> <?php if ($count > 1 && $k == 0) echo '<a href="#">Multiple</a>'; ?> <li <?php if ($count > 1) echo "style='display:none;'"; ?>><?= $asst->full_name; ?></li> <?php endforeach; ?> </ul> <?php endif; ?> 。在

count

您使用的for (int count = 0; count <= 100; count++) { int temp; cin >> temp; if (temp < 0) { break; } nums[count] = temp; count++; } 是for循环中声明的count。然后,当您执行

时,使用在main中声明的count
count

仍为nums[count + 1] = '\0'; Sort(nums, count);

你也会遇到

的问题
0

因为你永远不会检查while (nums[j - 1] > nums[j]) { tmp = nums[j]; nums[j] = nums[j - 1]; nums[j - 1] = tmp; j--; } 。如果j < 1,那么您的负索引是未定义的行为。