0

Need to use and measure the time it takes a randomized array to be sorted. I am getting a stack overflow error as shown here:

Unhandled exception at 0x00007FF64EEC2634 in COM301 Lab 3.exe: 0xC00000FD: Stack overflow (parameters: 0x0000000000000001, 0x0000004DB18B3FC8).

I think there is probably a few issues with my code, shown below. The quicksort is not exactly perfect but this was how I got it to work for smaller arrays. The error pops up in swap, but its not an issue with that I think. Here is the code:

#include <ctime>
#include <chrono>
#include <cstdlib>
#include <iostream>
#include <algorithm>

using namespace std;

#ifndef QuickSort
using namespace std;

static void swap(int arr[], int& x, int& y) {
    int temp = arr[x];
    arr[x] = arr[y];
    arr[y] = temp;
}

void minMax(int arr[], const int& size, int& min, int& max) { 
    for (int i = 0; i < size; i++) {
        if (arr[i] < min)
            min = arr[i];
        if (arr[i] > max)
            max = arr[i];
    }
}
//QuickSort:____________________________________________________________________________________________________________________________________________
//partitioning for quicksort
int partition(int arr[], int start, int end) {
    int pivot = arr[start]; //array is randomly generated, so pivot selection is trivial
    int i = start + 1;
    int j = end;

    while (i <= j) {    //While I is less than J, increment closer to the pivot until a suitable switch is found.
        while (i <= j && arr[i] < pivot)
            i++;
        while (i <= j && arr[j] > pivot)
            j--;
        if (i < j)
            swap(arr, i, j);    //suitable match found, switch i and j only if theyre not out of scope of their proper placement
        else
            break;
    }
    swap(arr, start, j);    //put pivot in its correct position

    return j;
}

void quickSort(int arr[], int start, int end) {
    if (start + 1 < end) { //as long as the array length is more than 1, continue recursing
        int p = partition(arr, start, end);

        //right side recursion
        quickSort(arr, p + 1, end);

        //left side recursion
        quickSort(arr, start, p);

        
    }
}

//MergeSort:_________________________________________________________________________________________________________

int main() {
//initialization of arrays, and array qualities
    const int size = 250;
    int max = 0;
    int min = 999999999;
    int arr[size];
    int arrC1[size], arrC2[size], arrC3[size], arrC4[size];

//Random generation seeded by the clock, as well as initialization of start/stop time variable
    srand(static_cast<unsigned>(time(0)));
    clock_t startTime, endTime;
    clock_t timeElapsed;

// Creation and printing of unsorted array  
    for (int i = 0; i < size; i++) {
        arr[i] = rand();
    }
    cout << "Randomly generated array(unsorted): \n";
    for(int i = 0; i < size; i++)
        cout << arr[i] << endl;


//copying of array to be used by sorting algorithms
    for (int i = 0; i < size; i++) {
        arrC1[i] = arr[i];
    }
    for (int i = 0; i < size; i++) {
        arrC2[i] = arr[i];
    }
    for (int i = 0; i < size; i++) {
        arrC3[i] = arr[i];
    }
    for (int i = 0; i < size; i++) {
        arrC4[i] = arr[i];
    }

//Run and print Quick sort
    startTime = clock();
    quickSort(arrC1, 0, size - 1);
    endTime = clock();
    timeElapsed = (endTime - startTime) * 1000;

    cout << "Start Time: " << startTime;
    cout << "\n End Time: " << endTime;
    cout << "\n \n \n Quick Sorted Array: \n";
    for (int i = 0; i < size; i++)
        cout << arrC1[i] << endl;
    cout << "Time Elapsed: " << timeElapsed;



}

I am a student, looking to get into the software engineering industry, so please be gentle with me. I would like to learn how to fix this in simple ways that are easy to understand if possible (I have some experience with programming but not much at this level). Additionally, I have issues with the clock() function so if anyone could show me an up to date fix that would be great. I need it in milliseconds/nanoseconds because seconds is way too big a number to measure.

Note: The code is very half-baked rn, I am just trying to fix the quick sort atm. I need to eventually implement merge sort, selection sort, etc. No help needed for that I just thought I'd mention it lol.

I've tried making swap static(didn't think it'd help but vss recommended it). I have also messed around with trying to make the integers used in the functions pointers to reduce memory usage but it messed with the operations done on them later. I've also messed with making the left side recursion end at p - 1 since I know that it is how quick sort is supposed to work (but it breaks what I have). I messed with the if (start + 1 < end) of the quickSort function but IDK how to properly optimize it. I've also tried setting the pivot differently but anything fancy I tried broke the program, even at the smaller array level. Really though I'm sure its something dumb that someone who knows quick sort could show me. If you can I'd really appreciate the help, thanks!

1
  • Sort the smaller subfile first to minimise stack usage. Commented Feb 17, 2024 at 5:37

2 Answers 2

0

This is where you get that error if (start < end) , rest will be fine

void quickSort(int arr[], int start, int end) {
    if (start < end) { // Correct condition
        int p = partition(arr, start, end);

        // Right side recursion, no change needed
        quickSort(arr, p + 1, end);

        // Left side recursion, exclude the pivot by subtracting 1
        quickSort(arr, start, p - 1);
    }
}
Sign up to request clarification or add additional context in comments.

Comments

0

To avoid stack overflow, recurse on the smaller partition, loop on the larger.

void quickSort(int arr[], int start, int end) {
    while (start < end) {
        int p = partition(arr, start, end);
        if(p - start <= end - p){       // recurse on smaller, loop on larger
            quickSort(arr, start, p);
            start = p + 1;
        } else {
            quickSort(arr, p + 1, end);
            end = p;
        }
    }
}

rand() is not that good. Here is a 32 bit pseudo random integer function:

// random 32 bit integer
int rnd32()
{
static uint32_t r = 0;
    r = r*1664525 + 1013904223;
    return (int)r;
}

Use new | delete[] for the arrays. Don't display large arrays. Check for array out of order.

int main() {
//initialization of arrays, and array qualities
    const int size = 16*1024*1024;
    int max = 0x80000000;
    int min = 0x7FFFFFFF;
    int i;
    int *arr   = new int [size];
    int *arrC1 = new int [size];
    int *arrC2 = new int [size];
    int *arrC3 = new int [size];
    int *arrC4 = new int [size];

// start/stop time variables
    clock_t startTime, endTime;
    clock_t timeElapsed;

// Creation and printing of unsorted array
    for (int i = 0; i < size; i++)
        arr[i] = rnd32();

//copying of array to be used by sorting algorithms
    for (int i = 0; i < size; i++)
    {
        arrC1[i] = arr[i];
        arrC2[i] = arr[i];
        arrC3[i] = arr[i];
        arrC4[i] = arr[i];
    }

//Run and print Quick sort
    startTime = clock();
    quickSort(arrC1, 0, size - 1);
    endTime = clock();
    for (i = 1; i < size; i++) {
        if (arrC1[i - 1] > arrC1[i])
            break;
    }
    if (i == size)
        cout << "passed" << endl;
    else
        cout << "failed" << endl;
    timeElapsed = (endTime - startTime) * 1000;
    cout << "Time Elapsed: " << timeElapsed << endl;
    delete[] arrC4;
    delete[] arrC3;
    delete[] arrC2;
    delete[] arrC1;
    delete[] arr;
    return 0;
}

2 Comments

So for the quickSort fix, wouldn't that miss a side? I tried implementing that but it says my arr is out of order
@Infinite - no, because it's in a while loop, not an if, so after recursing on the smaller partition, it loops back to handle the larger partition. This limits the number of level of recursions to ceil(log2(size)).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.