0% found this document useful (0 votes)
5 views2 pages

Java Insertion Sort Example Code

The document describes an implementation of insertion sort in Java. It generates a random array, prints it unsorted, then sorts it using insertion sort and prints the sorted array. It includes helper methods to create and print the arrays.

Uploaded by

salmanshokha
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views2 pages

Java Insertion Sort Example Code

The document describes an implementation of insertion sort in Java. It generates a random array, prints it unsorted, then sorts it using insertion sort and prints the sorted array. It includes helper methods to create and print the arrays.

Uploaded by

salmanshokha
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd

// Simple Java implementation of insertion sort

//
// Michael S. Tashbook, Stony Brook University
import [Link].*;
public class InsertionSort
{
public static void main (String [ ] args)
{
[Link]("Generating a list of random values...");
int [ ] list = createRandomArray(10); // change 10 to the # of your choi
ce
[Link]("Original (unsorted) list:");
printArray(list);
[Link]();
[Link]("Sorting list using insertion sort...");
insertionSort(list);
[Link]();
[Link]("Sorted list:");
printArray(list);
[Link]();
}
static void insertionSort (int [ ] list)
{
// Assume that the first element of the list is already sorted
printArrayMidSort(list, 0);
[Link]();
int firstUnsorted = 1;
while (firstUnsorted < [Link])
{
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);
[Link]();
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 = [Link](100) + 1;
numbers[i] = val;
}
return numbers;
}
static void printArray (int [ ] list)
{
for (int i = 0; i < [Link]; i++)
{
[Link](list[i]);
if (i < ([Link] - 1))
{
[Link](", ");
}
}
[Link]();
}
static void printArrayMidSort (int [ ] list, int startOfUnsorted)
{
[Link]("[ ");
for (int i = 0; i < [Link]; i++)
{
[Link](list[i] + " ");
if (i == startOfUnsorted)
{
[Link]("][ ");
}
}
[Link]("]");
}
}

You might also like