I have got an assignment to implement quicksort(pivot is always the first element of the array while partitioning). I am getting correct output for small arrays, but the assignment has a text file containing 10,000 integers. While sorting this input, I am getting stack overflow.
I tried allocating heap memory by using new
, but still getting the error. How to handle this?
Here is the code :
#include<iostream>
#include<fstream>
#include<string>
using namespace std;
const int len = 10000;
int counter = 0;
void qsort(int *arr1, int start1, int end1);
int partition(int *arr2, int start2, int end2);
int main(void)
{
int* arr = new int[len];
int i = 0;
fstream FILE;
FILE.open("text.txt");
if (FILE.is_open())
{
string line;
while (getline(FILE, line))
{
arr[i] = stoi(line);
i++;
}
FILE.close();
}
qsort(arr, 0, len - 1);
for (int i = 0; i < len; i++)
cout << arr[i];
cout << counter;
delete[] arr;
return 0;
}
void qsort(int* arr, int start, int end)
{
if (end - start == 0)
return;
else
{
counter += end - start;
int temp = partition(arr, start, end);
if (temp == end)
qsort(arr, start, temp - 1);
else if (temp == start)
qsort(arr, temp + 1, end);
else
{
qsort(arr, 0, temp - 1);
qsort(arr, temp + 1, end);
}
}
}
int partition(int* arr, int start, int end)
{
int pivot = arr[start];
int i = start, j = start;
for (; j <= end; j++)
{
if (arr[j] < pivot)
{
int temp = arr[i + 1];
arr[i + 1] = arr[j];
arr[j] = temp;
i++;
}
}
int tmp = arr[start];
arr[start] = arr[i];
arr[i] = tmp;
return i;
}