Исключение FirstChance StackOverFlow Слияние Сортировка Оболочка Сортировка Пузырьковая сортировка

Эй, ребята, я работаю над некоторыми видами сортировки и пытаюсь реализовать сортировку по пузырькам, сортировку по слиянию и сортировку по оболочке. Я использую устаревшую технику, но мне было интересно, если бы вы, ребята, могли сообщить мне, почему я продолжаю получать следующую ошибку:

Исключение первого шанса в 0x01135EF7 в sortApplication2.exe: 0xC00000FD: переполнение стека (параметры: 0x00000000, 0x00542000).
Необработанное исключение в 0x01135EF7 в sortApplication2.exe: 0xC00000FD: переполнение стека (параметры: 0x00000000, 0x00542000).

Я использую Visual Studio 2012, если это играет какую-либо роль. Мой код находится в трех разных файлах, поэтому я буду публиковать каждый отдельно.

Мой заголовочный файл:

#pragma once
class sort
{
public:
sort();
void random1(int array[]);
void random2(int array[]);
void random3(int array[]);
void bubbleSort(int array[], int length);
/*void merge(int *input, int p, int r);
void merge_sort(int *input, int p, int r);*/
void shellSort(int array[], int length);
};

Мой файл реализации класса:

#include "sort.h"#include <time.h>
#include <iostream>

using namespace std;

sort::sort()
{}

void sort::random1(int array[])
{
// Seed the random-number generator with current time so that
// the numbers will be different every time the program runs.
for(int i = 0; i < 25; i++)
{

srand ((unsigned) time(NULL));
int n = rand();     //generates a random number
array[i] = n;       //places it into the array
}

}
void sort::random2(int array[])
{
// Seed the random-number generator with current time so that
// the numbers will be different every time the program runs.
for(int i = 0; i < 10000; i++)
{
srand ((unsigned) time(NULL));
int n = rand();     //generates a random number
array[i] = n;       //places it into the array
}

}
void sort::random3(int array[])
{
// Seed the random-number generator with current time so that
// the numbers will be different every time the program runs.
for(int i = 0; i < 100000; i++)
{
srand ((unsigned) time(NULL));
int n = rand();     //generates a random number
array[i] = n;       //places it into the array
}
}
void sort::bubbleSort(int array[], int length)
{
//Bubble sort function

int i,j;

for(i = 0; i < 10; i++)
{
for(j = 0; j < i; j++)
{
if(array[i] > array[j])
{
int temp = array[i]; //swap
array[i] = array[j];
array[j] = temp;
}
}
}
}

/*void sort::merge(int* input, int p, int r) //the merge algorithm of the merge sort
{
int mid = (p + r) / 2;
int i1 = 0;
int i2 = p;
int i3 = mid + 1;

// Temp array
int x = r -p + 1;
int *temp;
temp = new int [x];

// Merge in sorted form the 2 arrays
while ( i2 <= mid && i3 <= r )
if ( input[i2] < input[i3] )
temp[i1++] = input[i2++];
else
temp[i1++] = input[i3++];
// Merge the remaining elements in left array
while ( i2 <= mid )
temp[i1++] = input[i2++];

// Merge the remaining elements in right array
while ( i3 <= r )
temp[i1++] = input[i3++];

// Move from temp array to master array
for ( int i = p; i <= r; i++ )
input[i] = temp[i-p];
}
void sort::merge_sort(int *input, int p, int r) //the merge sort algorithm
{
if ( p < r ) //When p and r are equal the recursion stops and the arrays are then     passed to the merge function.
{
int mid = (p + r) / 2;
merge_sort(input, p, mid); //recursively calling the sort function in order to     break the arrays down as far as possible
merge_sort(input, mid + 1, r);//recursively calling the sort function in order to     break the arrays down as far as possible
merge(input, p, r); //merge function realigns the smaller arrays into bigger arrays     until they are all one array again
}
}*/void sort::shellSort(int array[], int  length) //Shell sort algorithm
{
int gap, i, j, temp;
for( gap = length / 2; gap > 0; gap /= 2) //gap is the number of variables to skip when doing the comparisons
{
for( i = gap; i < length; i++) //This for loop sets the variable to use as the gap for the comparisons
{
for (j = i - gap; j >= 0 && array[j] > array[j + gap]; j -= gap)
{
temp = array[j]; //the array variables are swapped
array[j] = array[j + gap];
array[j + gap] = temp;
}
}
}
}

И мой файл драйвера:

#include "sort.h"#include <iostream>

using namespace std;

int main()
{
int bubbleArray1[25]; //these are the arrays to be sorted. three for each sort.     each has a length of 25, 10000, or 100000.
int bubbleArray2[10000];
int bubbleArray3[100000];
int mergeArray1[25];
int mergeArray2[10000];
int mergeArray3[100000];
int shellArray1[25];
int shellArray2[10000];
int shellArray3[100000];
sort Sorts;

Sorts.random1(bubbleArray1);
Sorts.random1(mergeArray1);
Sorts.random1(shellArray1);
Sorts.random2(bubbleArray2);
Sorts.random2(mergeArray2);
Sorts.random2(shellArray2);
Sorts.random3(bubbleArray3);
Sorts.random3(mergeArray3);
Sorts.random3(shellArray3);

cout << "BubbleSort1 is now being sorted.\n";
Sorts.bubbleSort(bubbleArray1, 25);
cout << "BubbleSort2 is now being sorted.\n";
Sorts.bubbleSort(bubbleArray2, 10000);
cout << "BubbleSort3 is now being sorted.\n";
Sorts.bubbleSort(bubbleArray3, 100000);
cout << "End bubble sorts.\n";

/*cout << "MergeSort1 is now being sorted.\n";
Sorts.merge_sort(mergeArray1, 0, 25);
cout << "MergeSort2 is now being sorted.\n";
Sorts.merge_sort(mergeArray2, 0, 10000);
cout << "MergeSort3 is now being sorted.\n";
Sorts.merge_sort(mergeArray3, 0, 100000);
cout << "End merge sorts.\n";*/

cout << "ShellSort1 is now being sorted.\n";
Sorts.shellSort(shellArray1, 25);
cout << "ShellSort1 is now being sorted.\n";
Sorts.shellSort(shellArray2, 10000);
cout << "ShellSort1 is now being sorted.\n";
Sorts.shellSort(shellArray3, 100000);
cout << "End shell sorts.\n";

cout << "Array\tElements\n";
cout << "BubbleSort1\t";
for(int i = 0; i < 25; i++)
{
cout << bubbleArray1[i] << " ";
}
cout << "\nMergeArray1\t";
for(int i = 0; i < 25; i++)
{
cout << mergeArray1[i] << " ";
}
cout << "\nShellArray1\t";
for(int i = 0; i < 25; i++)
{
cout << shellArray1[i] << " ";
}return 0;
}

Я знаю, что это много кода. И, возможно, есть много способов улучшить код.
Я просто хотел бы знать, что является причиной ошибки выше, так как я не могу найти ее с помощью моего компилятора.

0

Решение

Вы выделяете слишком много памяти в стеке. Переменные с «автоматическим» классом хранения помещаются в стек. Вместо этого выделите кучу.

Итак, вместо:

int shellArray3[100000];

Делать:

int* shellArray3 = new int[100000];

Или еще лучше, используйте std :: vector.

Если вы не хотите использовать кучу памяти, вы также можете использовать статический класс хранения для чего-то подобного. Для этого:

static int shellArray3[100000];

Это позволит выделить один экземпляр переменной для всей программы, а не выделять копию для каждой записи функции в стеке.

0

Другие решения

Других решений пока нет …

По вопросам рекламы ammmcru@yandex.ru
Adblock
detector