# Thread: Sorting an Array via Stacks

1. Member Join Date
Jan 2010
Posts
16
Rep Power
0

## Sorting an Array via Stacks

Hello, I am having an issue with sorting an array (initialArray) of 100 integers. The method to be used is having two stacks, and by using pop/push/top, and an algorithm, to create sortedArray, a sorted version of initialArray. I'm pretty sure my constructor and methods are correct, posted below.

Java Code:
```  public Lab1Stack ()
{
theArray = (int[]) new int ;
topOfStack = -1;
}

public boolean isEmpty()
{
if (topOfStack == -1)
return true;
else
return false;
}

public void push (int value)
{
theArray[++topOfStack] = value;
}

public int pop ()
{
return theArray[topOfStack--];
}

public int top ()
{
return theArray[topOfStack];
}```
But I am reading my proffesor's hint of the algorithm, and kind of getting confused. This is what I have so far.

Java Code:
```    Lab1Stack s1 = new Lab1Stack();
Lab1Stack s2 = new Lab1Stack();
int value;

for (int i=0; i<initialArray.length; i++)
{
while ((s1.isEmpty()== false) && (initialArray[i] < s1.top()))
{
value = s1.pop();
s2.push(value);
}
while ((s2.isEmpty() == false) && (initialArray[i] >= s2.top()))
{
value = s2.pop();
s1.push(value);
}

s2.push(initialArray[i]);
}```
It is kind of working, both arrays are being filled of and sorted, but sometimes 5 to 10 numbers are missing... Usually index 99 in the initialArray doesnt get popped into either object... Any help would be appreciated.

Oh yeah, at this point im just looking at the two arrays, I'm not popping values into my sortedArray yet since this isn't working.
Last edited by viperlasson; 02-01-2010 at 06:58 AM.  Reply With Quote

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•