程序崩溃序列排序程序

Program crash sequence sorting program

本文关键字:程序 排序 崩溃      更新时间:2023-10-16

在修复完错误后,我运行了程序,它崩溃了。尝试修复该程序一段时间,但无法修复。该程序是关于序列和排序的。编译器是devcpp。似乎不是堆栈溢出。:)

#include <iostream>
#include <cstdlib>
#include <ctime>
#include <iomanip> 
#include <conio.h>
using namespace std;
void selectionSort(int *, int);
int main()
{
    int N;
    int a[ N ];
    cout << "n Enter the length of sequence:";
    cin >> N;
    for (int i = 0; i < N && i < 5; ++i)
    {
        a[ N ] = rand() % 1000000 + 0;
        srand(time(0));
        cout << "Random sequence";
        for (int i = 0; i < N; i++)
            cout << setw(4) << a[i];
        cout << endl;
    }
    cout << "Sorted sequence";
    selectionSort(a, N);
    for (int j = 0; j < N; j++)
        cout << setw(4) << a[j];
    cout << endl;
    getch();
}
void selectionSort(int *array, int N)
{
    int temp, i, j;
    for (i = 0; i < N - 1; i++)
    {
        j = i;
        while (j > 0 && array [j - 1] > array [j])
        {
            temp = array [j];
            array[j] = array [j - 1];
            j--;
        }
    }
}

您正试图访问您不拥有的内存。

 int N;
 int a[ N ];

您正在声明N,然后用它定义数组,但此时它还没有初始化。然后,当你试图写入内存中的位置时,它会产生错误。

您正在定义一个具有可变N大小的数组。使用指示的:

int *a = new int[N];
// ...
delete [] a;

第二个问题是a[N] = ...,它是对不存在的元素的访问。

此外,最好将srand(time(0));放在代码的开头,而不是放在循环中。

int main()
{
    srand(time(0));
    int N;
    cout << "n Enter the length of sequence:";
    cin >> N;
    int *a = new int[N]; // If you compiler support you can: int a[N];
    for (int i = 0; i < N; ++i)
    {
        a[ i ] = rand() % 1000 + 0;
    }
    cout << "Random sequence";
    for (int j = 0; j < N; j++)
        cout << setw(4) << a[j];
    cout << endl;

    cout << "Sorted sequence";
    selectionSort(a, N);
    for (int j = 0; j < N; j++)
        cout << setw(4) << a[j];
    cout << endl;
    getch();
    delete [] a; // If you use pointer version
}