Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * Sort an unsorted array of ints using selection sort
- *
- * @author Ulizio
- * @version 1
- */
- import java.io.*;
- import java.util.*;
- import java.util.Scanner;
- public class SortProjectNums {
- public static void main(String [] args) {
- try {
- //Array Setup Section:
- Scanner scan = new Scanner(new BufferedReader(new FileReader("nums.txt")));
- int size = 0;
- while(scan.hasNextInt()) {
- size++;
- scan.nextInt();
- }
- //This list contains the raw numbers
- int [] nums = new int[size];
- //This list will store the sorted numbers
- int [] numsSorted = new int[size];
- scanNums(nums);
- System.out.println("The Unsorted List:");
- //print(nums);
- //Sorting Section:
- int count = 0;
- int min = nums[0];
- int i = 0;
- int currentInt = 0;
- int temp = 0;
- int minIndex = 0;
- for(count = 0; count < size; count++) {
- //This loop tracks the "round" we are on. The total number of rounds is how many times we run through the array.
- //Also regulates which sections are unsorted.
- min = nums[count];
- minIndex = count;
- for(i = count; i < size; i++) {
- //This loop runs through the entire array during each round and finds the minimum within the section that hasn't been sorted yet.
- currentInt = nums[i];
- if(currentInt < min) {
- min = nums[i];
- minIndex = i;
- }
- }
- temp = nums[minIndex];
- nums[minIndex] = nums[count];
- nums[count] = temp;
- }
- System.out.println("The Sorted List:");
- print(nums);
- }
- catch(Exception e) {
- System.out.println(e.getMessage());
- }
- }
- public static void scanNums(int [] array) {
- //Scan the ints into the array
- try {
- Scanner scan = new Scanner(new BufferedReader(new FileReader("nums.txt")));
- int i = 0;
- while(scan.hasNextInt()) {
- array[i] = scan.nextInt();
- i++;
- }
- } catch(Exception e) {
- System.out.println(e.getMessage());
- }
- }
- public static void print(int [] array) {
- int i = 0;
- for(i = 0; i < array.length; i++) {
- System.out.println(array[i]);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement