Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.io.*;
- import java.util.*;
- public class MergeSort {
- private static String[] sortedArray;
- private static String[] inputArray;
- public static void main (String[] args) {
- if (args.length != 2) {
- System.out.print("Need 2 arguments, please");
- } else {
- inputArray = readFile(args[0]);
- MergeSort(inputArray);
- writeFile(args[1], sortedArray);
- }
- }
- private static String[] readFile(String file_name) {
- try {
- Scanner in = new Scanner(new FileInputStream(file_name));
- int size = 0;
- while( in.hasNext() )
- size++;
- in.close();
- Scanner in2 = new Scanner(new FileInputStream(file_name));
- String[] arr = new String[size];
- int i = 0;
- while( in2.hasNext() )
- arr[i++] = in2.next().toLowerCase();
- return arr;
- }
- catch (Exception e) {
- throw new RuntimeException("Read not working\n");
- }
- }
- private static void writeFile(String file_name, String[] inputArray) {
- try {
- PrintStream output = new PrintStream( new FileOutputStream( file_name ) );
- for( int i = 0; i < sortedArray.length; i++ )
- output.println( sortedArray[i] );
- }
- catch (Exception e) {
- throw new RuntimeException("Write not working");
- }
- }
- private static void merge( String [ ] a, String [ ] tmpArray,
- int leftPos, int rightPos, int rightEnd ) {
- int leftEnd = rightPos - 1;
- int tmpPos = leftPos;
- int numElements = rightEnd - leftPos + 1;
- // Main loop
- while( leftPos <= leftEnd && rightPos <= rightEnd )
- if( a[ leftPos ].compareTo( a[ rightPos ] ) <= 0 )
- tmpArray[ tmpPos++ ] = a[ leftPos++ ];
- else
- tmpArray[ tmpPos++ ] = a[ rightPos++ ];
- while( leftPos <= leftEnd ) // Copy rest of first half
- tmpArray[ tmpPos++ ] = a[ leftPos++ ];
- while( rightPos <= rightEnd ) // Copy rest of right half
- tmpArray[ tmpPos++ ] = a[ rightPos++ ];
- // Copy tmpArray back
- for( int i = 0; i < numElements; i++, rightEnd-- )
- a[ rightEnd ] = tmpArray[ rightEnd ];
- }
- private static void Merge( String [ ] a, String [ ] tmpArray,
- int left, int right ) {
- if( left < right ) {
- int center = ( left + right ) / 2;
- Merge( a, tmpArray, left, center );
- Merge( a, tmpArray, center + 1, right );
- merge( a, tmpArray, left, center + 1, right );
- }
- }
- public static void MergeSort( String [ ] a) {
- String [ ] tmpArray = new String[ a.length ];
- Merge( a, tmpArray, 0, a.length - 1 );
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement