Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package csc355;
- import java.util.ArrayList;
- //LOVE WIKIPEDIA :)
- public class QuickSelectSequential
- {
- public static int select( int[ ] array, int k )
- {
- return select( array, 0, array.length - 1, k );
- }
- private static int select( int[ ] array, int left, int right, int k )
- {
- while( true )
- {
- if( right <= left + 1 )
- {
- if( right == left + 1 && array[ right ] < array[ left ] )
- {
- switcher( array, left, right );
- }
- return array[ k ];
- }
- else
- {
- int middle = ( left + right ) >>> 1;
- switcher( array, middle, left + 1 );
- if( array[ left ] > array[ right ] )
- {
- switcher( array, left, right );
- }
- if( array[ left + 1 ] > array[ right ] )
- {
- switcher( array, left + 1, right );
- }
- if( array[ left ] > array[ left + 1 ] )
- {
- switcher( array, left, left + 1 );
- }
- int l = left + 1;
- int m = right;
- int pivot = array[ left + 1 ];
- while( true )
- {
- do l++; while( array[ l ] < pivot );
- do m--; while( array[ m ] > pivot );
- if( m < l )
- {
- break;
- }
- switcher( array, l, m );
- }
- array[ left + 1 ] = array[ m ];
- array[ m ] = pivot;
- if( m >= k )
- {
- right = m - 1;
- }
- if( m <= k )
- {
- left = l;
- }
- }
- }
- }
- private static void switcher( int[ ] array, int n, int o )
- {
- int temporary = array[ n ];
- array[ n ] = array[ o ];
- array[ o ] = temporary;
- }
- ///TESTER
- public static void main( String[ ] args )
- {
- int[ ] input = { 1, 6, 4, 5, 8 };
- System.out.println( "The lowest number is: " + select( input, 0 ) );
- System.out.println( "The second lowest number is: " + select( input, 1 ) );
- System.out.println( "The third lowest number is: " + select( input, 2 ) );
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement