import java.util.StringTokenizer; import java.util.Scanner; /** Array.java -- Let's implement some simple sorting algorithms (ascending). */ public class Array { private int [] a; // Default constructor: Prompt the user to enter integers on one line. // The array can be any size, so we'll use the StringTokenizer. public Array() { System.out.print("Enter values for array: "); Scanner kbd = new Scanner(System.in); String line = kbd.nextLine(); // We have a choice. Use an ArrayList, or tokenize the line twice. // To make the sorting algorithms simpler to read, and faster, I chose // the array implementation. In realistic Java applications, we would // probably opt for the ArrayList or some more sophisticated data // structure. StringTokenizer tok = new StringTokenizer(line, " "); int numValues = 0; while (tok.hasMoreTokens()) { tok.nextToken(); ++numValues; } a = new int [numValues]; tok = new StringTokenizer(line, " "); for (int i = 0; i < numValues; ++i) a[i] = Integer.parseInt(tok.nextToken()); } public Array(Array otherArray) { int length = otherArray.a.length; a = new int[length]; for (int i = 0; i < length; ++i) a[i] = otherArray.a[i]; } // Constructor that a tester class can use on "true" arrays public Array(int [] otherArray) { int length = otherArray.length; a = new int[length]; for (int i = 0; i < length; ++i) a[i] = otherArray[i]; } // This constructor takes a String of values, e.g. "1 2 3" public Array(String s) { StringTokenizer tok = new StringTokenizer(s, " "); int n = tok.countTokens(); a = new int[n]; for (int i = 0; i < n; ++i) a[i] = Integer.parseInt(tok.nextToken()); } // Swap sort -- this one says to look at each distinct pair of elements, // and swap any that are out of order. public void swapSort() { int i, j; for (i = 0; i < a.length; ++i) for (j = i+1; j < a.length; ++j) { if (a[i] > a[j]) { int temp = a[i]; a[i] = a[j]; a[j] = temp; } } } // Selection sort: // For each position i in the array except the last 0..n-2, // find the *smallest* element from i..n-1 and swap it into position i. public void selectionSort() { // YOU NEED TO IMPLEMENT } // Insertion sort: Initially assume position 0 is sorted. // For each position i from 1..n-1, see how far left i can be inserted. // We'll need an inner loop to move elements right to make room for i. public void insertionSort() { // YOU NEED TO IMPLEMENT } // In Bubble Sort, we do the following n-1 times: // For each element i from 0..n-2, compare it to its neighbor i+1, and // swap if necessary. public void bubbleSort() { int pass, i; for (pass = 0; pass < a.length - 1; ++pass) { for (i = 0; i < a.length - 1; ++i) { if (a[i] > a[i+1]) { int temp = a[i]; a[i] = a[i+1]; a[i+1] = temp; } } } } public String toString() { StringBuilder sb = new StringBuilder(); for (int i = 0; i < a.length; ++i) sb.append(String.format("%d ", a[i])); return sb.toString(); } }