Welcome to Dream.In.Code
Become a C++ Expert!

Join 149,960 C++ Programmers for FREE! Get instant access to thousands of C++ experts, tutorials, code snippets, and more! There are 1,348 people online right now. Registration is fast and FREE... Join Now!




Non-Recursive QuickSort (using Stack)

 
Reply to this topicStart new topic

Non-Recursive QuickSort (using Stack)

dmd1120
7 Jan, 2008 - 03:55 PM
Post #1

New D.I.C Head
*

Joined: 21 Nov, 2007
Posts: 6


My Contributions
Hello again. I am frustrated, because none of the code in my textbook will actually compile, making it harder for me to figure out how to do some of this stuff! Anyway, I have an assignment whereby I have to write a non-recursive version of quicksort. The instructor did post some info, but I don't quite understand, and went my own way. However, I have come to a stop. I know that I have to change the value of the rightStart variable once I partition, but I am not sure where I should do this.

I can get it to compile, but I know there are some logical errors in there somewhere. If it's easier for you to find any logical errors, I can include all code so that you can simply compile it. For now, I am just including the 2 main functions. Also, I am wondering if, by doing it this way, I have made the assignment more difficult than is necessary? I appreciate any and all help I can get on this.

CODE


#include <cstdlib>
#include <iostream>
#include <stack>
using namespace std;

#define ARRAY_SIZE 20

//    Prototype Declarations
void fillArray(int numArray[]);
void quickSortNR(int data[]);
void medianToLeft(int data[], int left,  int right);
void sortSide(int data[], int &start, const int end);

int main (void)
{
//    Local Declarations
    int i;
    int ary[ARRAY_SIZE];

//    Statements

    fillArray(ary);

    quickSortNR(ary);

    return 0;
}    // main

void fillArray(int numArray[])
{
    for(int x = 0; x < ARRAY_SIZE; x++)
    {
        numArray[x] = rand() % 49 + 1;
    }
} // end fillArray

/*    =============== medianToLeft ================
    Find the median value of an array, data[left..right],
    and place it in the location data[left].
       Pre  data is an array of at least three elements
             left and right are the boundaries of the array
       Post  median value placed at data[left]
*/
void medianToLeft (int data[],
                 int left,
                 int right)
{
//    Local Definitions
    int mid;
    int hold;

//    Statements
    //    Rearrange sortData so median is in middle location  
    mid = (left + right) / 2;
    if (data[left] > data[mid])
       {
        hold = data[left];
        data[left] = data[mid];
        data[mid] = hold;
       } // if
    if (data[left] > data[right])
       {
        hold = data[left];
        data[left] = data[right];
        data[right] = hold;
       } // if
    if (data[mid] > data[right])
       {
        hold = data[mid];
        data[mid] = data[right];
        data[right] = hold;
       } // if
    // Median is in middle. Exchange with left.
    hold = data[left];
    data[left] = data[mid];
    data[mid] = hold;

    return;
}    // medianToLeft

/*    ================ quickSortNR =================
    Array data[] is sorted without recursion.
       @pre   data is an array of data to be sorted
       @post  data array is sorted
*/
void quickSortNR  (int data[])
{
//    Local Definitions
    int sorted = 0;        // keeps track of the number of sorted items
                        // and also determines start for next sort.
    int rightStart = ARRAY_SIZE;    // Starting point of the
                                    // right partition
                
    medianToLeft(data, sorted, rightStart);
    sortSide(data, sorted, rightStart);    // split to left and right
    
    while(sorted <= rightStart)
    {
        medianToLeft(data, sorted, rightStart);
        sortSide(data, sorted, rightStart);    // sort left side
    }
    while(sorted < ARRAY_SIZE)
    {
        medianToLeft(data, sorted, ARRAY_SIZE);
        sortSide(data, sorted, ARRAY_SIZE);    // sort right side
    } // end while
} // end quickSortNR

/* ========== sortSide ================
    This function will 'partition' the array using a stack.  
    If either partition has 3 or less items, then those are
    automatically sorted.
    @pre    There are items in the array
    @post    Items in the array are placed in order of
            < pivot; pivot; > pivot                */
void sortSide(int data[], int &start, int end)
{
    // Local Declarations
    int pivotVal = data[start-1];    // temporary variable to
                                    // hold the value of the pivot    
    stack<int> lStack;
    stack<int> rStack;
    int stSize = 0;    // # of items in stack
    int cur = start + 1;
    int temp;
    
    // Statements
    while(cur < end)    // traverse through the items
                        // in the array (skip pivot)
    {
        // separate items into left and right stacks
        if(data[cur] < pivotVal)
            lStack.push(data[cur]);
        else
            rStack.push(data[cur]);

        cur++;
    } // end while
    cur = start;    // reset cur variable
    stSize = lStack.size(); // get size of stack before
                            // moving back to array.
    while (!lStack.empty())
    {
        data[cur] = lStack.top();
        lStack.pop();
        cur++;
    }

    /*    If there are 3 or less items in the stack,
        sort them without using another stack    */
    switch(stSize)
        {
        case 3:    
            start+= 4;    //items in left stack
                        //and pivot are sorted.
            if(data[cur] > data[cur+1])
            {
                int temp = data[cur];
                data[cur] = data[cur+1];
                data[cur+1] = temp;
            }
            if(data[cur] > data[cur+1])
            {
                temp = data[cur];
                data[cur] = data[cur+1];
                data[cur+1] = temp;
            }
            if(data[cur+1] > data[cur+2])
            {
                temp = data[cur+1];
                data[cur+1] = data[cur+2];
                data[cur+2] = temp;
            }
            break;
        case 2:
            start += 3;
            if(data[cur] > data[cur+1])
            {
                int temp = data[cur];
                data[cur] = data[cur+1];
                data[cur+1] = temp;
            }
            break;
        case 1:
            start += 2;
            break;
        case 0:
            start++;
            break;
    } // end switch

    data[cur] = pivotVal;
    start++;
    cur++;        

    // SORT THE RIGHT SIDE
    stSize = rStack.size(); // get size of stack before
                            // moving back to array.
    while (!rStack.empty())
    {
        data[cur] = rStack.top();
        rStack.pop();
        cur++;
    }

    /*    If there are 3 or less items in the stack,
        sort them without using another stack    */
    switch(stSize)
        {
        case 3:    
            start+= 4;    //items in left stack
                        //and pivot are sorted.
            if(data[cur] > data[cur+1])
            {
                int temp = data[cur];
                data[cur] = data[cur+1];
                data[cur+1] = temp;
            }
            if(data[cur] > data[cur+1])
            {
                temp = data[cur];
                data[cur] = data[cur+1];
                data[cur+1] = temp;
            }
            if(data[cur+1] > data[cur+2])
            {
                temp = data[cur+1];
                data[cur+1] = data[cur+2];
                data[cur+2] = temp;
            }
            break;
        case 2:
            start += 3;
            if(data[cur] > data[cur+1])
            {
                int temp = data[cur];
                data[cur] = data[cur+1];
                data[cur+1] = temp;
            }
            break;
        case 1:
            start += 2;
            break;
        case 0:
            start++;
            break;
    } // end switch

    data[cur] = pivotVal;
    start++;
    cur++;        
} // end sortSide



This post has been edited by dmd1120: 7 Jan, 2008 - 04:21 PM
User is offlineProfile CardPM
+Quote Post

Tom9729
RE: Non-Recursive QuickSort (using Stack)
7 Jan, 2008 - 04:07 PM
Post #2

Debian guru
Group Icon

Joined: 30 Dec, 2007
Posts: 1,591



Thanked: 12 times
Dream Kudos: 325
My Contributions
It would be more helpful if we could see all the code.

On a separate note, what errors are you getting trying to compile the examples in your book?
User is online!Profile CardPM
+Quote Post

dmd1120
RE: Non-Recursive QuickSort (using Stack)
7 Jan, 2008 - 04:31 PM
Post #3

New D.I.C Head
*

Joined: 21 Nov, 2007
Posts: 6


My Contributions
QUOTE(Tom9729 @ 7 Jan, 2008 - 05:07 PM) *

It would be more helpful if we could see all the code.

On a separate note, what errors are you getting trying to compile the examples in your book?



Ok, I just edited my original post to include all the code from the program.

In regards to the book, I guess I'm disappointed because there are no actual example programs that I can type in to see it work. It's all just little snippets, and although I don't remember the compile errors I had been getting, I still have yet to get any of them to work properly. My brother recently gave me one of his old textbooks from a Data Structures class, and that has been helpful. However, I've spent so much time on this horrible book, that I don't have much more time to complete the class... therefore, I don't know how much time I'll have to read the better book. the book he gave me is older, though... published in 2000. The quicksort in that book is actually rather different from the quicksort code in my textbook, too. I intend to comment on the poor quality of the book when I fill out my end-of-class survey. The school has been pretty receptive to my comments in the past, so hopefully they'll change this book for future students.
User is offlineProfile CardPM
+Quote Post

Tom9729
RE: Non-Recursive QuickSort (using Stack)
7 Jan, 2008 - 04:50 PM
Post #4

Debian guru
Group Icon

Joined: 30 Dec, 2007
Posts: 1,591



Thanked: 12 times
Dream Kudos: 325
My Contributions
There are lots of nice tutorials online if you know where to look. smile.gif

By the way, I haven't looked through your code extensively but it just segfaulted when I tried to run it.

CODE

Program received signal SIGSEGV, Segmentation fault.
0x0804918e in main () at h.c:27
27      }    // main

User is online!Profile CardPM
+Quote Post

William_Wilson
RE: Non-Recursive QuickSort (using Stack)
7 Jan, 2008 - 05:12 PM
Post #5

lost in compilation
Group Icon

Joined: 23 Dec, 2005
Posts: 4,101



Thanked: 25 times
Dream Kudos: 3275
Expert In: Java, C, Javascript

My Contributions
I threw in a method to print the array out and it's over writing with huge negative values, i'm assuming are garbage or an address and not generated by your code. Seems there is an address written to the array somewhere, i'm not positive on that, but i'll look into it more a little later
User is offlineProfile CardPM
+Quote Post

dmd1120
RE: Non-Recursive QuickSort (using Stack)
7 Jan, 2008 - 05:15 PM
Post #6

New D.I.C Head
*

Joined: 21 Nov, 2007
Posts: 6


My Contributions
QUOTE(Tom9729 @ 7 Jan, 2008 - 05:50 PM) *

There are lots of nice tutorials online if you know where to look. smile.gif

By the way, I haven't looked through your code extensively but it just segfaulted when I tried to run it.

CODE

Program received signal SIGSEGV, Segmentation fault.
0x0804918e in main () at h.c:27
27      }    // main



I don't get any errors when compiling, but I hadn't tried to actually run the program until you mentioned the Segfault. I don't get that error, but I get
CODE

Run-Time Check Failure #2 - Stack around the variable 'ary' was corrupted.

User is offlineProfile CardPM
+Quote Post

Reply to this topicStart new topic
Time is now: 1/8/09 06:15PM

Be Social

Dream.In.Code RSS Feed Dream.In.Code LinkedIn Group Follow Us On Twitter

Live C++ Help!

C++ Tutorials

Reference Sheets

C++ Snippets

DIC Chatroom

Bye Bye Ads

Monthly Drawing

Thumb Drive

Top Contributors

Top 10 Kudos This Month