Advertisement
Guest User

IanAndCJClickHerePlease

a guest
Apr 23rd, 2019
87
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.56 KB | None | 0 0
  1. package csc355;
  2.  
  3. import java.util.ArrayList;
  4.  
  5. //LOVE WIKIPEDIA :)
  6. public class QuickSelectSequential
  7. {
  8. public static int select( int[ ] array, int k )
  9. {
  10. return select( array, 0, array.length - 1, k );
  11. }
  12.  
  13. private static int select( int[ ] array, int left, int right, int k )
  14. {
  15.  
  16. while( true )
  17. {
  18.  
  19. if( right <= left + 1 )
  20. {
  21.  
  22. if( right == left + 1 && array[ right ] < array[ left ] )
  23. {
  24. switcher( array, left, right );
  25. }
  26.  
  27. return array[ k ];
  28.  
  29. }
  30. else
  31. {
  32.  
  33. int middle = ( left + right ) >>> 1;
  34. switcher( array, middle, left + 1 );
  35.  
  36. if( array[ left ] > array[ right ] )
  37. {
  38. switcher( array, left, right );
  39. }
  40.  
  41. if( array[ left + 1 ] > array[ right ] )
  42. {
  43. switcher( array, left + 1, right );
  44. }
  45.  
  46. if( array[ left ] > array[ left + 1 ] )
  47. {
  48. switcher( array, left, left + 1 );
  49. }
  50.  
  51. int l = left + 1;
  52. int m = right;
  53. int pivot = array[ left + 1 ];
  54.  
  55. while( true )
  56. {
  57. do l++; while( array[ l ] < pivot );
  58. do m--; while( array[ m ] > pivot );
  59.  
  60. if( m < l )
  61. {
  62. break;
  63. }
  64.  
  65. switcher( array, l, m );
  66. }
  67.  
  68. array[ left + 1 ] = array[ m ];
  69. array[ m ] = pivot;
  70.  
  71. if( m >= k )
  72. {
  73. right = m - 1;
  74. }
  75.  
  76. if( m <= k )
  77. {
  78. left = l;
  79. }
  80. }
  81. }
  82. }
  83.  
  84. private static void switcher( int[ ] array, int n, int o )
  85. {
  86. int temporary = array[ n ];
  87. array[ n ] = array[ o ];
  88. array[ o ] = temporary;
  89. }
  90.  
  91. ///TESTER
  92. public static void main( String[ ] args )
  93. {
  94.  
  95. int[ ] input = { 1, 6, 4, 5, 8 };
  96.  
  97. System.out.println( "The lowest number is: " + select( input, 0 ) );
  98. System.out.println( "The second lowest number is: " + select( input, 1 ) );
  99. System.out.println( "The third lowest number is: " + select( input, 2 ) );
  100. }
  101. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement