fork download
  1. import java.text.ParseException;
  2. import java.time.Duration;
  3. import java.time.LocalTime;
  4. import java.util.Random;
  5. import java.util.function.BiConsumer;
  6.  
  7. class Ideone {
  8.  
  9. private static final int NB_TEST = 10_000;
  10.  
  11. public static void main( String[] args ) throws ParseException {
  12. int[] indexes = new Random().ints( NB_TEST, 0, Integer.MAX_VALUE ).toArray();
  13.  
  14. String[] sources = new String[indexes.length],
  15. targets = new String[indexes.length];
  16.  
  17. for ( int i = 0; i < indexes.length; ++i ) {
  18. sources[i] = "sources #" + i;
  19. targets[i] = "targets #" + i;
  20. }
  21.  
  22. LocalTime start = LocalTime.now();
  23. {
  24. Sorter.sortArrays( indexes, ( i, j ) -> swapCell( sources, i, j ), ( i, j ) -> swapCell( targets, i, j ) );
  25. }
  26. LocalTime end = LocalTime.now();
  27.  
  28. System.out.println( Duration.between( start, end ) );
  29. }
  30.  
  31. public static <T> void swapCell( T[] array, int from, int to ) {
  32. T tmp = array[from];
  33. array[from] = array[to];
  34. array[to] = tmp;
  35. }
  36. }
  37.  
  38. interface Sorter {
  39. void sort( int[] array, BiConsumer<Integer, Integer>... actions );
  40.  
  41. static void sortArrays( int[] array, BiConsumer<Integer, Integer>... actions ) {
  42. if ( array.length < 1000 )
  43. new BubbleSorter().sort(array, actions);
  44. else
  45. new SelectionSorter().sort(array, actions);
  46. }
  47. }
  48.  
  49. class SelectionSorter implements Sorter {
  50. @Override
  51. public void sort( int[] array, BiConsumer<Integer, Integer>... actions ) {
  52. int index;
  53. int value;
  54. int tmp;
  55. for ( int i = 0, length = array.length; i < length; ++i ) {
  56. index = i;
  57. value = array[i];
  58. for ( int j = i + 1; j < length; ++j )
  59. if ( value > array[j] ) {
  60. index = j;
  61. value = array[j];
  62. }
  63.  
  64. if ( index != i ) {
  65. tmp = array[i];
  66. array[i] = array[index];
  67. array[index] = tmp;
  68.  
  69. // Swap the other arrays
  70. for ( BiConsumer<Integer, Integer> cons : actions )
  71. cons.accept( i, index );
  72. }
  73. }
  74. }
  75. }
  76.  
  77. class BubbleSorter implements Sorter {
  78. @Override
  79. public void sort( int[] array, BiConsumer<Integer, Integer>... actions ) {
  80. int tmp;
  81.  
  82. boolean swapped;
  83. do {
  84. swapped = false;
  85. for ( int i = 1, length = array.length; i < length; ++i )
  86. if ( array[i - 1] > array[i] ) {
  87. tmp = array[i];
  88. array[i] = array[i - 1];
  89. array[i - 1] = tmp;
  90.  
  91. // Swap the other arrays
  92. for ( BiConsumer<Integer, Integer> cons : actions )
  93. cons.accept( i, i - 1 );
  94.  
  95. swapped = true;
  96. }
  97. } while ( swapped );
  98. }
  99. }
Success #stdin #stdout 0.29s 38776KB
stdin
Standard input is empty
stdout
PT0.077S