Download as txt, pdf, or txt
Download as txt, pdf, or txt
You are on page 1of 2

// Simple Java implementation of insertion sort

//
// 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

int [ ] numbers = new int[size];


Random r = new Random();
for (int i = 0; i < size; i++)
{
int val = r.nextInt(100) + 1;
numbers[i] = val;
}
return numbers;
}
static void printArray (int [ ] list)
{
for (int i = 0; i < list.length; i++)
{
System.out.print(list[i]);
if (i < (list.length - 1))
{
System.out.print(", ");
}
}
System.out.println();
}
static void printArrayMidSort (int [ ] list, int startOfUnsorted)
{
System.out.print("[ ");
for (int i = 0; i < list.length; i++)
{
System.out.print(list[i] + " ");
if (i == startOfUnsorted)
{
System.out.print("][ ");
}
}
System.out.println("]");
}
}

You might also like