Ds 4
Ds 4
Problem Description:
You are given an array of N integers. Your task is to sort the array in
ascending order using the Bubble Sort algorithm. The algorithm should
repeatedly compare adjacent elements and swap them if they are in the
wrong order, until the entire array is sorted.
return 0;
}
Test case1:
b) Insertion Sort Algorithm:
Insertion Sort is a simple and efficient sorting algorithm that builds the
sorted array one element at a time by inserting each element into its
correct position.
Program:
#include<stdio.h>
int main()
{
int a[10],i,j,temp,n;
printf("enter no of elements");
scanf("%d",&n);
printf("enter the elements into the array");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
printf("before sorting\t");
for(i=0;i<n;i++)
{
printf("%d\t",a[i]);
}
for(i=1;i<n;i++)
{
temp=a[i];
j=i-1;
while(j>=0 && a[j]>temp)
{
a[j+1]=a[j];
j--;
}
a[j+1]=temp;
}
printf("\nafter sorting\t");
for(i=0;i<n;i++)
{
printf("%d\t",a[i]);
}
return 0;
}
Selection Sort is a simple sorting algorithm that divides the array into
sorted and unsorted parts and repeatedly selects the smallest
element from the unsorted part to place it in its correct position.
Program:
#include<stdio.h>
int main()
{
int a[10],i,j,temp,n;
printf("enter no of elements");
scanf("%d",&n);
printf("enter the elements into the array");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
printf("before sorting\t");
for(i=0;i<n;i++)
{
printf("%d\t",a[i]);
}
for(i=1;i<n;i++)
{
temp=a[i];
j=i-1;
while(j>=0 && a[j]>temp)
{
a[j+1]=a[j];
j--;
}
a[j+1]=temp;
}
printf("\nafter sorting\t");
for(i=0;i<n;i++)
{
printf("%d\t",a[i]);
}
return 0;
}
Input and Output Processing:
Conclusion:
Insertion Sort is generally the most efficient among the three for
small or nearly sorted data.
Selection Sort performs fewer swaps than Bubble Sort but is still
inefficient for large datasets.
Bubble Sort is the least efficient as it makes the most swaps but
is useful for learning purposes.
All three algorithms have O(n²) worst-case complexity,
making them impractical for large datasets.