Insertion sort is a sorting technique used to sort array in ascending and descending order.
For other sorting programs click
https://java4school.com/array-programs-part-1-icse-computer-applications
Write a program to accept an array from the user and sort the array in ascending order using the insertion sort method.
import java.io.*;
class insertion_sort {
public static void main()throws IOException {
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the length of the Array.");
int n=Integer.parseInt(br.readLine());
int Arr[]=new int[n];
int sum=0;
System.out.println("Enter the values");
for(int i=0;i<n;i++)
Arr[i]=Integer.parseInt(br.readLine());
System.out.println("\f");
for(int i=0;i<n;i++)
System.out.println(Arr[i]);
int flag, j;
for(int i=1;i<n;i++) {
flag=Arr[i];
j=i-1;
while(j>=0 && Arr[j]>flag)
{
Arr[j+1]=Arr[j];
j=j-1;
}
Arr[j+1]=flag;
} System.out.println("Sorted Array is ");
for(int i=0;i<n;i++)
System.out.println(Arr[i]);
} }
Output:
Enter the length of the Array.
4
Enter the values
23
17
2
4
Sorted Array is
2
4
17
23
For more java videos click
https://www.youtube.com/user/trushnatej