1

Im currently working with merge sort. I am trying to write a program that reads a file full of numbers, asks the user if they want it sorted in ascending, descending, or both. and then write another file. I have gotten to the point where I am able to read the file, and sort it in ascending order, but hit a wall and don't know what to do next.

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;

public class mergesortapp{

    public void mergeSort(Integer[] array, int lo, int n) {
        int low = lo;
        int high = n;
        if (low >= high) {
            return;
        }

        int middle = (low + high) / 2;
        mergeSort(array, low, middle);
        mergeSort(array, middle + 1, high);
        int end_low = middle;
        int start_high = middle + 1;
        while ((lo <= end_low) && (start_high <= high)) {
            if (array[low] < array[start_high]) {
                low++;
            } else {
                int Temp = array[start_high];
                for (int k = start_high - 1; k >= low; k--) {
                    array[k + 1] = array[k];
                }
                array[low] = Temp;
                low++;
                end_low++;
                start_high++;
            }
        }
    }

    public static void main(String[] args) throws NumberFormatException, IOException {
    Final pb = new Final();
        try {
            BufferedReader br = new BufferedReader(new FileReader("/TextFile"));
            List<Integer> lines = new ArrayList<Integer>();
            String line;
            while ((line = br.readLine()) != null) {
                lines.add(Integer.parseInt(line));
            }
            br.close();
            Integer[] inputArray = lines.toArray(new Integer[lines.size()]);
            pb.mergeSort(inputArray, 0, inputArray.length - 1);
            System.out.println("Here is your list of numbers that you requested: ");
            for (Integer i : inputArray) {
                System.out.println(i);
            }
        } catch (IOException ie) {
            System.out.print(ie.getMessage());
        }

    }
jtate
  • 2,155
  • 6
  • 24
  • 31
john
  • 11
  • 1
  • 1
    where exactly have you hit a wall? – jtate Oct 13 '18 at 17:22
  • The wall I have hit is how to get the users input for whether they want it in ascending order, descending order, or both. – john Oct 13 '18 at 18:04
  • You can use the scanner-class for reading from the console (System.in): https://docs.oracle.com/javase/10/docs/api/java/util/Scanner.html. There are a lot of examples in the net for this, e.g. https://stackoverflow.com/questions/19950713/scanner-input-validation-in-while-loop. – Topaco Oct 14 '18 at 09:30

0 Answers0