Question

I keep getting an unhandled exception in this portion of code whenever it runs, I have looked through it and can't see a clear reason. It will run fine up to the system pause that is commented out so it has to be something past that.Or maybe it is how I am setting my pivot?

template <class elemType>
int arrayListType<elemType>::medianpartition(int p, int r)
{
    int middle = list[(r+p)/2];
    int pivot = 0;

    if(list[p]<list[r]){
        if(middle<list[r]){
            if(list[p]<middle){
                pivot = middle;
            }else if(list[p]>middle){
                pivot = list[p];
            }
        }else if(middle>list[r]){
            pivot = list[r];
        }
    }else if(list[p]>list[r]){
        if(middle<list[r]){
            pivot = list[r];
        }else if(middle>list[r]){
            if(middle<list[p]){
                pivot = middle;
            }else if(middle>list[p]){
                pivot = list[p];
            }
        }
    }

    //system("Pause>nul");

    while ( p < r )
    {
        while ( list[p] < pivot )
            p++;

        while ( list[r] > pivot )
            r--;

        if ( list[p] == list[r] )
            p++;
        else if ( p < r )
        {
            int tmp = list[p];
            list[p] = list[r];
            list[r] = tmp;
        }
    }

    return r;
}

This is the function that calls it:

template <class elemType>
void arrayListType<elemType>::medianquicksort(int p, int r)
{
    if ( p < r )
    {
        int j = medianpartition(p, r);        
        medianquicksort(p, j-1);
        medianquicksort(j+1, r);
    }
}

Any help would be appreciated!

Was it helpful?

Solution

If list[p] == list[r] then pivot is not assigned any value from the array and stays with its default value of zero. And if all items of the array are greater than zero, or all are less than zero, then one of the while loops runs p or r out of array's bounds.

OTHER TIPS

Think about this: what happens if every element in your array is the same value?

You have too many if else if statements when trying to figure out the pivot, and you didn't account for the possibility that list[p], list[r] and/or middle have the same value. I don't know if that's the root of your problem, but it's certainly a problem.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top