// Dan Grossman // CSE142, Spring 2009 // A class with two static methods that sort integer arrays. // One uses the insertion sort algorithm; the other uses the // selection sort algorithm. main provides several tests. import java.util.*; public class SortIntegerArray { // (external behavior: the purpose of a method comment) // return a new array that has the same contents as the argument, but // in sorted order. Does not change the argument (which is important // due to references). public static int[] sort(int[] unsorted) { // (internal algorithm: not visible to callers) // uses the "insertion sort" algorithm int[] sorted = new int[unsorted.length]; // for each element in the argument... // after i iterations, we are using the first i positions // in sorted for(int i=0; i < unsorted.length; i++) { int j = 0; // find where unsorted[i] should go while(j < i && unsorted[i] > sorted[j]) { j++; } // move everybody over to make room // tricky: important to start "on the right" // note: works even if 0 elements need to shift for(int k=i; k > j; k--) { sorted[k] = sorted[k-1]; } sorted[j] = unsorted[i]; } return sorted; } // external behavior exactly the same as sort to show there are // different sorting algorthms public static int[] anotherSort(int[] unsorted) { // (internal algorithm: not visible to callers) // uses the "selection sort" algorithm int[] sorted = new int[unsorted.length]; boolean[] used = new boolean[unsorted.length]; // initialized to false implicitly // repeatedly copy over the smallest element that // hasn't been moved over yet for(int i=0; i < unsorted.length; i++) { // find first not-moved-over, put its _index_ in j int j = 0; while(used[j]) { j++; } // now find smallest not-moved over and put its index in j int least = unsorted[j]; for(int k=j+1; k < unsorted.length; k++) { if(!used[k] && unsorted[k] < unsorted[j]) { j = k; least = unsorted[k]; } } // move it over and mark it used sorted[i] = least; used[j] = true; } return sorted; } public static void testSort(int[] arr) { System.out.println("initial array:\t" + Arrays.toString(arr)); System.out.println("sort result:\t" + Arrays.toString(sort(arr))); System.out.println("another result:\t" + Arrays.toString(anotherSort(arr))); System.out.println(); } public static void main(String[] args) { int arr1[] = {3, 2, 4, 4, 8, 0, -3, 7}; int arr2[] = {1, 2, 3, 4, 5, 4, 3, 2, 1}; int arr3[] = {}; int arr4[] = {9}; int arr5[] = {3, 3, 3, 3, 4, 2}; testSort(arr1); testSort(arr2); testSort(arr3); testSort(arr4); testSort(arr5); } }