Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * Sorts an unordered file of Strings using the insertion method
- * Only after finishing did I realize the similarity to selection sort
- *
- * Thanks for the extension, it was well used.
- *
- * @author Ulizio
- * @version 6
- */
- import java.lang.Math;
- import java.io.*;
- import java.util.*;
- import java.util.Scanner;
- public class SortProjectStrings
- {
- public static void main(String [] args) {
- try {
- //Array Creation Section:
- Scanner scan = new Scanner(new BufferedReader(new FileReader("words.txt")));
- int size = 0;
- while(scan.hasNext()) {
- size++;
- scan.next();
- }
- String [] strs = new String[size];
- scanStrs(strs);
- System.out.println("The Unsorted List:");
- print(strs);
- scan.close();
- //Moved code to method to simplify
- sort(strs);
- System.out.println("");
- System.out.println("");
- System.out.println("");
- System.out.println("The Sorted List:");
- print(strs);
- } catch(Exception e) {
- System.out.println(e.getMessage());
- }
- }
- public static void scanStrs(String [] array) {
- //Here we will sort through the strings on file as we scan them into the array to
- try {
- Scanner scan = new Scanner(new BufferedReader(new FileReader("words.txt")));
- int i = 0;
- while(scan.hasNext()) {
- array[i] = scan.next();
- i++;
- }
- } catch(Exception e) {
- System.out.println(e.getMessage());
- }
- }
- public static void print(String [] array) {
- int i = 0;
- for(i = 0; i < array.length; i++) {
- System.out.println(array[i]);
- }
- }
- public static void sort(String [] strs) {
- try {
- int currentIndex = 0;
- int count = 0;
- //No longer necessary
- //String a = strs[currentIndex];
- //String b = strs[currentIndex + 1];
- String temp = "";
- //int max = (int) Math.pow(size, 4);
- int x = 0;
- //Needs to start at 1 because x is decrementing(checks the index before count)
- for(count = 1; count < strs.length; count++) {
- //This loop runs through each indices, then executes the sorting (below) for each index effectively
- //currentIndex = 0;
- //Temp
- temp = strs[count];
- //To conserve the # of loops we'll evaluate both conditions here. Should help with skipping issue I was having
- for(x = count - 1; x >= 0 && temp.compareToIgnoreCase(strs[x]) < 0; x--) {
- //This part of the loop runs through the process for each indices
- //The wikipedia gif shows a "slide" involved
- //This chunk "slides" the values as we go.
- //Swap
- strs[x + 1] = strs[x];
- }
- strs[x + 1] = temp;
- //System.out.println("--------------------");
- //print(strs);
- }
- //System.out.println("--------------------");
- //print(strs);
- }
- catch(Exception e) {
- System.out.println(e.getMessage());
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement