Advertisement
Guest User

Untitled

a guest
Jun 25th, 2017
62
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.83 KB | None | 0 0
  1.  
  2. import java.io.*;
  3. import java.util.*;
  4.  
  5. public class MergeSort {
  6.  
  7. private static String[] sortedArray;
  8. private static String[] inputArray;
  9. public static void main (String[] args) {
  10. if (args.length != 2) {
  11. System.out.print("Need 2 arguments, please");
  12. } else {
  13. inputArray = readFile(args[0]);
  14. MergeSort(inputArray);
  15. writeFile(args[1], sortedArray);
  16. }
  17. }
  18.  
  19. private static String[] readFile(String file_name) {
  20. try {
  21. Scanner in = new Scanner(new FileInputStream(file_name));
  22. int size = 0;
  23. while( in.hasNext() )
  24. size++;
  25. in.close();
  26. Scanner in2 = new Scanner(new FileInputStream(file_name));
  27. String[] arr = new String[size];
  28. int i = 0;
  29. while( in2.hasNext() )
  30. arr[i++] = in2.next().toLowerCase();
  31. return arr;
  32. }
  33. catch (Exception e) {
  34. throw new RuntimeException("Read not working\n");
  35. }
  36.  
  37. }
  38. private static void writeFile(String file_name, String[] inputArray) {
  39. try {
  40. PrintStream output = new PrintStream( new FileOutputStream( file_name ) );
  41. for( int i = 0; i < sortedArray.length; i++ )
  42. output.println( sortedArray[i] );
  43. }
  44.  
  45. catch (Exception e) {
  46. throw new RuntimeException("Write not working");
  47. }
  48. }
  49.  
  50.  
  51. private static void merge( String [ ] a, String [ ] tmpArray,
  52. int leftPos, int rightPos, int rightEnd ) {
  53. int leftEnd = rightPos - 1;
  54. int tmpPos = leftPos;
  55. int numElements = rightEnd - leftPos + 1;
  56.  
  57. // Main loop
  58. while( leftPos <= leftEnd && rightPos <= rightEnd )
  59. if( a[ leftPos ].compareTo( a[ rightPos ] ) <= 0 )
  60. tmpArray[ tmpPos++ ] = a[ leftPos++ ];
  61. else
  62. tmpArray[ tmpPos++ ] = a[ rightPos++ ];
  63.  
  64. while( leftPos <= leftEnd ) // Copy rest of first half
  65. tmpArray[ tmpPos++ ] = a[ leftPos++ ];
  66.  
  67. while( rightPos <= rightEnd ) // Copy rest of right half
  68. tmpArray[ tmpPos++ ] = a[ rightPos++ ];
  69.  
  70. // Copy tmpArray back
  71. for( int i = 0; i < numElements; i++, rightEnd-- )
  72. a[ rightEnd ] = tmpArray[ rightEnd ];
  73. }
  74.  
  75. private static void Merge( String [ ] a, String [ ] tmpArray,
  76. int left, int right ) {
  77. if( left < right ) {
  78. int center = ( left + right ) / 2;
  79. Merge( a, tmpArray, left, center );
  80. Merge( a, tmpArray, center + 1, right );
  81. merge( a, tmpArray, left, center + 1, right );
  82. }
  83. }
  84.  
  85. public static void MergeSort( String [ ] a) {
  86. String [ ] tmpArray = new String[ a.length ];
  87. Merge( a, tmpArray, 0, a.length - 1 );
  88. }
  89. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement