Monday, 26 August 2013

pancake sorting using decrease and conquer

pancake sorting using decrease and conquer

Please help me to solve my problem. This is one of our case studies.
Here's my code and I dont know what's the error here. It doesn't sort all
the pancakes according to their sizes. the largest one should be at the
bottom place or at the last position in array. Here's my code.
package pancake;
import java.io.*;
import java.util.*;
import static pancake.Pancake.processStack;
public class Pancake
{
public static void main (String args[]) // entry point from OS
{
Scanner s, ls;
int pancakes[] = new int[300];
int k;
s = new Scanner(System.in); // create new input Scanner
while(s.hasNextLine()) /* While there's more data to process... */
{
/* Read the integers */
ls = new Scanner(s.nextLine());
k = 0;
while (ls.hasNextInt())
pancakes[k++] = ls.nextInt();
processStack(pancakes, k);
}
}
public static void processStack(int pancakes[], int L)
{
int bottom, max_so_far, index, i, j, k;
/* Print out the stack again */
System.out.print("Flip sequence: ");
for (bottom = L-1; bottom > 0; bottom--)
{ /* First, find a maximum of the
substack of elements
pancakes[0], pancakes[bottom]*/
index = bottom;
max_so_far = pancakes[bottom];
for (i = bottom - 1; i >= 0; i--)
if (pancakes[i] > max_so_far)
{
max_so_far = pancakes[i];
index = i;
}
/* Now, if we have to flip anything... */
if (index != bottom)
{
if (index != 0) /* if we have to flip something
other than the one on top */
System.out.print( (index+1) + " ");
/* then we flip this one */
System.out.print( (bottom+1) + " ");
/* Now construct the new stack. Note that I'm
not explicitly performing the flip(s) that
would be performed, but am directly
constructing it by copying portions of
the stack of pancakes.
If you carefully study what I'm doing here,
you should be able to follow along and see
that it's correct, i.e., that I end up with
the stack that would be present after performing
the one or two flips to bring the next
largest pancake into position.
*/
int temp[] = new int[L];
j = 0;
for (i = bottom; i > index; i--, j++)
temp[j] = pancakes[i];
for (i = 0; i < index; i++, j++)
temp[j] = pancakes[i];
temp[j++] = pancakes[index];
/* Having constructed the new (top) portion,
insert it back into the array for the next
time through the loop.
*/
for (i = 0; i <= bottom; i++)
pancakes[i] = temp[i];
} /* end of performing the next flip(s), if
necessary */
}
System.out.println`enter code here`();
}
}

No comments:

Post a Comment