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

Lab 12

Uploaded by

f23mmg06
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)
5 views

Lab 12

Uploaded by

f23mmg06
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/ 2

Aror University of Art, Architecture, Design and Heritage

SUKKUR, Sindh
Department of Multimedia and Gaming
Course: Data Structures CSC-221 (Practical)
Instructor: Engr. Fatima Jaffar

LAB 10

Objective: Understanding and Implementing Insertion Sort Algorithm

Introduction:
Insertion sort is a simple sorting algorithm that works by iteratively inserting
each element of an unsorted list into its correct position in a sorted portion of
the list. It is like sorting playing cards in your hands. You split the cards into
two groups: the sorted cards and the unsorted cards. Then, you pick a card from
the unsorted group and put it in the right place in the sorted group.

Algorithm:
 We start with second element of the array as first element in the array is
assumed to be sorted.
 Compare second element with the first element and check if the second
element is smaller then swap them.
 Move to the third element and compare it with the first two elements and
put at its correct position
 Repeat until the entire array is sorted.
Time Complexity of Insertion Sort
 Best case: O(n) , If the list is already sorted, where n is the number of
elements in the list.
 Average case: O(n 2 ) , If the list is randomly ordered
 Worst case: O(n 2 ) , If the list is in reverse order

Lab Task
Implement Insertion sort algorithm in java.

/*
* Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change
this license
*/

package com.mycompany.mavenproject20;

public class Mavenproject20 {

public static void main(String[] args) {


int arr[]={4,6,7,8,5,3,2};
for(int i=1; i<arr.length;i++)
{
int key = arr[i];
int j=i-1;
while(j<=0 && arr[j]>key){
arr[j+1]= arr[j];
j--;
}
arr[j+ 1]=key;
}
for(int i=0;i<arr.length;i++) {
System.out.println(i+ " ");

}
}
}

You might also like