0% found this document useful (0 votes)
7 views

1 d Insertion Sorting

The document outlines a Java program for performing insertion sort, detailing the algorithm and providing the source code. It includes steps for reading input, sorting the array, and displaying the results before and after sorting. The program was executed successfully, confirming the correct implementation of the insertion sort algorithm.

Uploaded by

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

1 d Insertion Sorting

The document outlines a Java program for performing insertion sort, detailing the algorithm and providing the source code. It includes steps for reading input, sorting the array, and displaying the results before and after sorting. The program was executed successfully, confirming the correct implementation of the insertion sort algorithm.

Uploaded by

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

EX NO: 1D INSERTION SORT PAGE NO:

DATE:

AIM:
To write a java program for performing insertion sort.

ALGORITHM:

Step 1:Read the number of elements (n) and array elements.


Step 2:Input n elements into the array a.
Step 3:Display the array elements before
sorting.
Step 4:Set the current element as key for
each element from the second
position (i is equal to 1) to the last
position.
Step 5:Compare key with elements before
it (a[j] where j is equal to i - 1).
Step 6:Shift all elements larger than key
one position to the right.
Step 7:Place key in its correct sorted
position.
Step 8:Display the array elements after
sorting.

PROGRAM:
import java.util.Scanner;
class Insertionsort
{
public static void main(String args[])
{
int n,i,j,key;
int a[]=new int[100];
Scanner s=new Scanner(System.in);
System.out.print("Enter the no of elements:");
n=s.nextInt();
System.out.println("Enter the elements");
for(i=0;i<n;i++)
{
a[i]=s.nextInt();
}
System.out.println("Before Sorting");
for(i=0;i<n;i++)
{
System.out.println(a[i]);
}
for(i=1;i<n;i++)
{
key=a[i];
j=i-1;
while(j>=0 && a[j]>key)
{
a[j+1] = a[j];
j=j-1;
}
a[j+1] = key;
}
System.out.println("After Sorting");
for(i=0;i<n;i++)
{
System.out.println(a[i]);
}
}
}
OUTPUT:

RESULT:
Thus the java program for performing insertion sort was executed and the output was
verified successfully.

You might also like