Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.io.BufferedReader;
- import java.io.File;
- import java.io.FileReader;
- import java.io.IOException;
- public class Selection {
- public static void main(String[] args) {
- // assign private instance array to an array of 20
- int[] intArray = new int[20];
- // reads numbers from file
- try {
- File file = new File("\\Input.txt");
- BufferedReader input = new BufferedReader(new FileReader(file));
- String line = null;
- while ((line = input.readLine()) != null) {
- try {
- String[] tokens = line.split(" ");
- int arrayPosition = 0;
- for (String t : tokens) {
- int x = Integer.parseInt(line);
- intArray[arrayPosition] = x;
- arrayPosition++;
- }
- } catch (Exception e) {
- System.out.println("File contained a non-integer");
- }
- }
- } catch (IOException e) {
- System.out.println("File does not exist");
- }
- System.out.print("Data: ");
- for (int x : intArray) {
- System.out.print(x + " ");
- }
- System.out.println("\n");
- sort(intArray);
- // read from file and insert into array of 20
- // pass it into sort method
- // print it to console
- }
- public static void print(int[] intArray, int passNumber) {
- System.out.print("Pass " + passNumber + ": ");
- for (int c : intArray) {
- System.out.print(c + " ");
- }
- System.out.println("\n");
- }
- public static void sort(int[] intArray) {
- // blank array
- int[] tempArray;
- // starting position
- for (int x = 0; x <= intArray.length - 1; x++) {
- // assign tempArray to a new empty array of length array.length-1
- // resets array to be blank with every loop
- tempArray = new int[intArray.length];
- // position of minInt
- int minIntPos = -1;
- int minInt = Integer.MAX_VALUE;
- // finds minimum number and sets it to minInt
- for (int y = x; y <= intArray.length - 1; y++) {
- if (minInt > intArray[y]) {
- minInt = intArray[y];
- minIntPos = y;
- }
- }
- // insert minInt to position x in the new array
- tempArray[x] = minInt;
- // loop through old array and insert into positions after (excluding
- // position at minInt)
- for (int z = x; z <= intArray.length - 1; z++) {
- if (z < minIntPos) {
- int newPos = z + 1;
- tempArray[newPos] = intArray[z];
- } else if (z != minIntPos)
- tempArray[z] = intArray[z];
- }
- // assign array to be new array
- System.arraycopy(tempArray, x, intArray, x, intArray.length - x);
- print(intArray, x);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement