InsertionSort Java
InsertionSort Java
//
// Michael S. Tashbook, Stony Brook University
import java.util.*;
public class InsertionSort
{
public static void main (String [ ] args)
{
System.out.println("Generating a list of random values...");
int [ ] list = createRandomArray(10); // change 10 to the # of your choi
ce
System.out.println("Original (unsorted) list:");
printArray(list);
System.out.println();
System.out.println("Sorting list using insertion sort...");
insertionSort(list);
System.out.println();
System.out.println("Sorted list:");
printArray(list);
System.out.println();
}
static void insertionSort (int [ ] list)
{
// Assume that the first element of the list is already sorted
printArrayMidSort(list, 0);
System.out.println();
int firstUnsorted = 1;
while (firstUnsorted < list.length)
{
int valToSort = list[firstUnsorted];
int pos = firstUnsorted;
while (pos > 0 && list[pos-1] > valToSort)
{
list[pos] = list[pos-1]; // move another large sorted value over
pos--; // move toward the front of the list
}
// Put the new value into its proper position in the sorted region
list[pos] = valToSort;
printArrayMidSort(list, firstUnsorted);
System.out.println();
firstUnsorted++; // shrink the size of the undorted region by 1
}
}
// Helper methods
static int [] createRandomArray(int size)
{
// Create and return a list of 'size' randomly-generated integers betwee
n 1 and 100