Exp 1
Exp 1
01
Name: Vedaant Dinesh Ambolkar Roll No: 05
Date:28/1/2025
Theory:
Insertion sort
Selection sort
Algorithms:
Algorithm INSERTION-SORT()
for i = 1 to n-1:
key = array[i]
j=i-1
array[j + 1] = key
Algorithm SELECTION-SORT()
for i = 0 to n-2:
min_index = i
min_index = j
if min_index != i:
Complexity:
Insertion Sort:
Best Case Analysis: O(n)
Worst Case Analysis: O(n^2)
Average Case Analysis: O(n^2)
Selection Sort:
Best Case Analysis: O(n^2)
Worst Case Analysis: O(n^2)
Average Case Analysis: O(n^2)
#include<stdio.h>
#include<conio.h>
void main()
{ int key;
int n=10,i,j;
int arr[10];
scanf("%d",&n);
for(i=0;i<n;i++)
scanf("%d",&arr[i]);
for(i=0;i<n;i++)
printf("%d",arr[i]);
printf("\n");
for(j=1;j<=n-1;j++)
key =arr[j];
i=j-1;
while(i>=0 && arr[i]>key)
arr[i+1]=arr[i];
i=i-1;
arr[i+1]=key;
for(i=0;i<n;i++)
printf("%d",arr[i]);
getch();
OUT PUT
Program 2: Selection Sort and output
#include<stdio.h>
#include<conio.h>
int i,j,temp;
for(i=0;i<n-1;i++)
int min=i;
for(j=i+1;j<n;j++){
min = j;
}
temp = arr[min];
arr[min] = arr[i];
arr[i] = temp;
int main(){
int i;
int n = sizeof(arr)/sizeof(arr[0]);
clrscr();
sorting(arr , n);
printf("%d ",arr[i]);
getch();
return 0;
}
OUT PUT
ANS=> nsertion Sort and Selection Sort are both simple, comparison-based
sorting algorithms, but they differ in their approaches and efficiency.
Insertion Sort works similarly to how we arrange playing cards in our hands.
It builds the sorted sequence one element at a time by taking each element
and inserting it into its correct position within the already sorted portion of
the array. This makes it efficient when dealing with nearly sorted data, as its
best-case time complexity is O(n). However, in the worst and average cases,
its time complexity is O(n²), making it less efficient for large datasets.
On the other hand, Selection Sort works by repeatedly finding the smallest
element from the unsorted part and swapping it with the first unsorted
element. Unlike Insertion Sort, it does not adapt well to nearly sorted data
since it always performs O(n²) comparisons regardless of the input order.
However, it makes at most O(n) swaps, making it more efficient in scenarios
where swapping is costly.