/* Read numbers from a text file and store them into an array; then sort the array and display it on the screen. Save the sorted array in sorted.txt. */ import java.io.*; class ArraySort1 { static public void main(String[] args) throws IOException { BufferedReader stdin= new BufferedReader (new InputStreamReader (System.in)); String inputpath; System.out.print ("Enter the pathname of the input file: "); System.out.flush (); inputpath = stdin.readLine(); BufferedReader inputFile = new BufferedReader (new FileReader(inputpath)); /* Initialize the output stream writing into a text file */ PrintWriter outputFile = new PrintWriter (new FileWriter ("sorted.txt")); /* Declare the array */ int[] numbers = new int[50]; int index = 0; int temp, smallest, smallest_index; /* Read the first number */ numbers[index] = Integer.parseInt(inputFile.readLine()); while (numbers[index] != 0) { index++; numbers[index] = Integer.parseInt(inputFile.readLine()); } /* Sort the array using the selection sort method; the inner loop finds the smallest unsorted number, and the outer loop places it in the right place. */ for (int i = 0; i < index - 1; i++) { smallest = numbers[i]; smallest_index = i; for (int j = i + 1; j < index; j++) { if (numbers[j] < smallest) { smallest = numbers[j]; smallest_index = j; } } /* If needed switch numbers[i] and numbers[smallest_index] */ if (numbers[i] != numbers[smallest_index]) { temp = numbers[i]; numbers[i] = numbers[smallest_index]; numbers[smallest_index] = temp; } } /* Display the sorted array and also save the result in sorted.txt*/ for (int i = 0; i < index; i++) { System.out.print (numbers[i] + " "); outputFile.print (numbers[i] + " "); } inputFile.close(); outputFile.close(); } }