• Source
    1. /* package whatever; // don't place package name! */
    2.  
    3. import java.util.*;
    4. import java.lang.*;
    5. import java.io.*;
    6. import java.io.BufferedReader;
    7. import java.io.FileReader;
    8. import java.io.IOException;
    9.  
    10.  
    11. /* Name of the class has to be "Main" only if the class is public. */
    12. class Ideone
    13. {
    14.  
    15. static long swapCount = 0;
    16. public static void main(String[] args) {
    17.  
    18. // int[] input = new int[100000];
    19. // readInputIntoArray(input);
    20.  
    21. int[] input = {6,5,4,3,2,1};
    22.  
    23. mergeSort(input);
    24. System.out.println(swapCount);
    25. // print("", input);
    26. }
    27.  
    28.  
    29. private static void print(String pre, int[] a) {
    30. System.out.println(pre);
    31. for (int i = 0; i < a.length; i++) {
    32. System.out.print(" " + a[i] + " ");
    33. }
    34. System.out.println();
    35. }
    36.  
    37. private static void mergeSort(int[] a) {
    38. // print("recusion input : ", a);
    39. if (a.length == 0 || a.length == 1)
    40. return;
    41.  
    42. int mid = a.length / 2;
    43. int[] left = new int[mid];
    44. for (int i = 0; i < mid; i++) {
    45. left[i] = a[i];
    46. }
    47. // print("Before merge recursion left:", left);
    48.  
    49. int[] right = new int[a.length - mid];
    50. int temp = mid;
    51. for (int i = 0; temp < a.length;) {
    52. right[i++] = a[temp++];
    53. }
    54. // print("Before merge recursion right:", right);
    55.  
    56. mergeSort(left);
    57. mergeSort(right);
    58.  
    59. // print("Before left:", left);
    60. // print("Before right:", right);
    61.  
    62. int i = 0;
    63. int j = 0;
    64. int k = 0;
    65. while (i < left.length && j < right.length) {
    66. if (left[i] <= right[j]) {
    67. a[k++] = left[i++];
    68. } else {
    69. a[k++] = right[j++];
    70. swapCount += (mid-i);
    71. }
    72. }
    73.  
    74. while (i < left.length) {
    75. a[k++] = left[i++];
    76. }
    77.  
    78. while (j < right.length) {
    79. a[k++] = right[j++];
    80. }
    81.  
    82. // print("After merge:", a);
    83. }
    84.  
    85. private static void readInputIntoArray(int[] input) {
    86. BufferedReader br = null;
    87.  
    88. int i = 0;
    89. try {
    90. String sCurrentLine = null;
    91. br = new BufferedReader(new FileReader("input.text"));
    92. while ((sCurrentLine = br.readLine()) != null) {
    93. input[i++] = Integer.parseInt(sCurrentLine);
    94. }
    95. } catch (IOException e) {
    96. System.out.println("exception => " + e);
    97. }
    98. }
    99. }
    100.