Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package sort;
- import java.io.FileReader;
- import java.io.FileWriter;
- import java.io.IOException;
- import java.util.Arrays;
- import java.util.Scanner;
- class Main {
- private static int[] parseStringToArray(String data) {
- String[] numbers = data.split(" ");
- int[] arr = new int[numbers.length];
- for (int i = 0; i < numbers.length; i++) {
- arr[i] = Integer.parseInt(numbers[i]);
- }
- return arr;
- }
- private static int[] readFromFile() throws IOException {
- System.out.println("Enter file name");
- Scanner in = new Scanner(System.in);
- String fileName = in.nextLine();
- in = new Scanner(new FileReader(fileName));
- return parseStringToArray(in.nextLine());
- }
- private static int[] readFromConsole() {
- System.out.println("Enter an array");
- Scanner in = new Scanner(System.in);
- return parseStringToArray(in.nextLine());
- }
- private static void writeArrayToFile(int[] array) throws IOException {
- StringBuilder outputString = new StringBuilder();
- for (int i = 0; i < array.length; i++) {
- outputString.append(array[i]).append(" ");
- }
- System.out.println("Enter file name:");
- Scanner in = new Scanner(System.in);
- String fileName = in.nextLine();
- FileWriter out = new FileWriter(fileName, false);
- out.write(outputString.toString());
- out.flush();
- out.close();
- System.out.println("Saved to " + fileName);
- }
- public static void main(String[] args) throws IOException {
- int[] array;
- System.out.println("Theme: Sort an array using recursive selection sort \nPick an option:\n1 - Read from file\n2 - Read from console");
- Scanner in = new Scanner(System.in);
- int option = in.nextInt();
- in.nextLine();
- switch (option) {
- case 1:
- array = readFromFile();
- break;
- case 2:
- array = readFromConsole();
- break;
- default:
- array = new int[0];
- break;
- }
- System.out.println("Initial array: " + Arrays.toString(array));
- recursiveSort(array, array.length, 0);
- System.out.println("Result: " + Arrays.toString(array));
- System.out.println("Save the result to a file?\n1 - Yes\n2 - No");
- option = in.nextInt();
- if (option == 1) {
- writeArrayToFile(array);
- } else {
- System.out.println("File not saved");
- }
- }
- static int minIndex(int[] array, int i, int j)
- {
- if (i == j)
- return i;
- int k = minIndex(array, i + 1, j);
- return (array[i] < array[k])? i : k;
- }
- static void recursiveSort(int[] array, int n, int index)
- {
- if (index == n)
- return;
- int k = minIndex(array, index, n-1);
- if (k != index) {
- int temp = array[k];
- array[k] = array[index];
- array[index] = temp;
- }
- recursiveSort(array, n, index + 1);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement