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

Insertion Sort

Insertion sort

Uploaded by

jones.codyxxx
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views

Insertion Sort

Insertion sort

Uploaded by

jones.codyxxx
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 2

ASSIGNMENT 4: 29/4/24

Design a class Insertion_Sort that inputs an array from the user and sorts it in ascending order using
Insertion Sort technique. A main class is created to give details of the constructor and the member
methods.
Data Members -
int ar[] - Integer array to store numbers
int l - to store array length
Member Methods -
Insertion_Sort()- A constructor to initialize data members to 0.
void input()- To input the array from the user and store it in ar[].
void sort() - To sort ar[] in ascending order.
void display() - To display the sorted array.

import java.util.*;
class Insertion_Sort_Diganta Biswas
{ //start of class
int ar[];
int l;
Insertion_Sort_ Diganta Biswas ()
{
ar = new int[0];
l = 0;
}

void input()
{
System.out.print("Enter the length of the array: ");
Scanner sc=new Scanner(System.in);
l = sc.nextInt();
ar = new int[l];
System.out.println("Enter the elements of the array:");
for (int i = 0; i < l; i++)
{
ar[i] = sc.nextInt();
}
}

void sort()
{ //To sort the array
for (int i = 1; i < l; i++)
{
int t = ar[i];
int j = i - 1;
while (j >= 0 && ar[j] > t)
{
ar[j + 1] = ar[j];
j--;
}
ar[j + 1] = t;
}
}

void display()
{ //To display the sorted array
System.out.println("The sorted array is:");
for (int i = 0; i < l; i++)
{
System.out.print(ar[i] + " ");
}
System.out.println();
}

public static void main()


{ //start of main
Insertion_Sort_ Diganta Biswas ob = new Insertion_Sort_ Diganta Biswas ();
ob.input();
ob.sort();
ob.display();
} //end of main
} //end of class

OUTPUT
Enter the length of the array: 5
Enter the elements of the array:
20
65
48
25
98
The sorted array is:
20 25 48 65 98

Variable Description:-
Name Datatype Purpose
ar[] int Integer array to store numbers
l int to store array length
i int loop variable
j int loop variable
t int temporary variable

You might also like