0% found this document useful (0 votes)
21 views1 page

Insertion Sort in Java

The document provides a Java implementation of the insertion sort algorithm. It sorts an array of integers in ascending order by comparing each element with the elements before it and placing it in the correct position. The main method demonstrates the sorting of a sample array and prints the sorted result.

Uploaded by

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

Insertion Sort in Java

The document provides a Java implementation of the insertion sort algorithm. It sorts an array of integers in ascending order by comparing each element with the elements before it and placing it in the correct position. The main method demonstrates the sorting of a sample array and prints the sorted result.

Uploaded by

Prangobinda Sahu
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 1

// Insertion sort in Java

import java.util.Arrays;
class InsertionSort
{
void insertionSort(int array[])
{
int size = array.length;
for (int step = 1; step < size; step++)
{
int key = array[step];
int j = step - 1;
// Compare key with each element on the left of it until
// an element smaller than it is found.
// For descending order, change key<array[j] to key>array[j].
while (j >= 0 && key < array[j])
{
array[j + 1] = array[j];
--j;
}
// Place key at after the element just smaller than it.
array[j + 1] = key;
}
}
// Driver code
public static void main(String args[])
{
int[] data = { 9, 5, 1, 4, 3 };
InsertionSort is = new InsertionSort();
is.insertionSort(data);
System.out.println("Sorted Array in Ascending Order: ");
System.out.println(Arrays.toString(data));
}
}

You might also like