Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.Scanner;
- import java.io.*;
- public class PancakeSortNew {
- /**
- * Using an existing scanner, use it to fill an array of integers.
- * Returns the number of values found.
- */
- static int scanIntegerArray( int[] array, Scanner scan )
- {
- int i = 0;
- while( scan.hasNextInt())
- array[i++] = scan.nextInt();
- return i;
- }
- // returns the index of the largest element in a range of
- // array values. Assumes that last >= first.
- static int findMax( int[] array, int first, int last )
- {
- int index = first;
- int max = array[index];
- for( int i = first+1; i <= last; i++)
- {
- if( array[i] > max) {
- max = array[i];
- index = i;
- }
- }
- return index;
- }
- // reverse array elements within a given range
- // Assumes that last >= first.
- static void flip( int[] array, int first, int last )
- {
- int mid = (last-first) / 2 + 1;
- int temp;
- for( int i = 0; i < mid; i++ ) {
- temp = array[last-i];
- array[last-i] = array[first+i];
- array[first+i] = temp;
- }
- }
- // prints integer array in space-delimited format
- static void print( int[] array)
- {
- int size = array.length;
- for( int i = 0; i < size; i++ )
- System.out.print( array[i] + " " );
- System.out.println();
- }
- private static boolean Ordered(int[] array, int size){
- for(int i=0; i < size-1; i++)
- if(array[i] > array[i+1])
- return false;
- return true;
- }
- /**
- * Sorts an array of integers by repeatedly reversing
- * subranges within the array. Prints the flip sequence.
- */
- static void sortHelper(int[] array, int i)
- {
- if (i<=0) {
- System.out.println ( 0 );
- }
- int size = array.length;
- if (!Ordered(array, i)){
- int j = findMax(array, 0, i);
- int flipPosition;
- if( j != i )
- {
- if( j != 0 ) {
- flip( array, 0, j );
- flipPosition = size-j;
- System.out.print( flipPosition + " " );
- }
- flip( array, 0, i );
- flipPosition = size-i;
- System.out.print( flipPosition + " " );
- }
- }
- sortHelper(array, i-1);
- }
- public static void sort (int []array){
- sortHelper(array, array.length-1);
- }
- public static void main(String[] args)
- {
- final int MAX_INPUTS = 30;
- int[] array = new int[MAX_INPUTS];
- Scanner Input = new Scanner( System.in );
- while( Input.hasNextLine() )
- {
- String inputLine = Input.nextLine();
- Scanner scan = new Scanner( inputLine );
- // scan a string with a sequence of integers into an array
- int numbers = scanIntegerArray( array, scan );
- // Store the sequence of flips for later printing. Might be
- // larger than the number of input values. Check for possible
- // blank line in input file.
- if( numbers > 0 )
- {
- int[] output = new int[numbers];
- for (int i = 0; i < numbers ; i++){
- output[i] = array[i];}
- // print the original array
- print(output);
- // do the flipping
- sort( output);
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement