Write a complete C programme to implement the following sorting algor.docx
1. Write a complete C programme to implement the following
sorting algorithms: c. Bubble sort d. Selection sort e. Insertion
sort f. Merge sort g. Quick sort
Solution
C) BUBBLE SORT :
Bubble sort, sometimes referred to as sinking sort, is a simple
sorting algorithm that repeatedly steps through the list to be
sorted, compares each pair of adjacent items and swaps them if
they are in the wrong order.
D) SELECTION SORT :
Selection sort is a simple sorting algorithm. This sorting
algorithm is a in-place comparison based algorithm in which the
list is divided into two parts, sorted part at left end and unsorted
part at right end. Initially sorted part is empty and unsorted part
is entire list.
Program :
e) Insertion Sort :
Insertion sort is a simple sorting algorithm that builds the final
sorted array (or list) one item at a time. It is much less efficient
on large lists than more advanced algorithms such as quicksort,
heapsort, or merge sort.
2. Program :
f. Merge Sort :
merge sort first divide the list into the smallest unit (1 element),
then compare each element with the adjacent list to sort and
merge the two adjacent lists. Finally all the elements are sorted
and merged.
Program :
#include<stdio.h>
#include<conio.h>
void merge(int [],int ,int ,int );
void part(int [],int ,int );
int main()
{
int arr[30];
int i,size;
printf(" t------- Merge sorting method ------- ");
printf("Enter total no. of elements : ");
scanf("%d",&size);
for(i=0; i<size; i++)
{
printf("Enter %d element : ",i+1);
scanf("%d",&arr[i]);
}
part(arr,0,size-1);
printf(" t------- Merge sorted elements ------- ");
5. {
tmp[i]=arr[k];
i++;
}
}
for(k=min; k<=max; k++)
arr[k]=tmp[k];
}
g) Quick Sort :
The quicksort algorithm is performed as follows:
This is repeated until the entire array is sorted.
Program :
#include<stdio.h>
#include<conio.h>
void qsort(int arr[20], int fst, int last);
int main()
{
int arr[30];
int i,size;
printf("Enter total no. of the elements : ");
scanf("%d",&size);
printf("Enter total %d elements : ",size);
for(i=0; i<size; i++)
scanf("%d",&arr[i]);
6. qsort(arr,0,size-1);
printf("Quick sorted elements are as : ");
for(i=0; i<size; i++)
printf("%dt",arr[i]);
getch();
return 0;
}
void qsort(int arr[20], int fst, int last)
{
int i,j,pivot,tmp;
if(fst<last)
{
pivot=fst;
i=fst;
j=last;
while(i<j)
{
while(arr[i]<=arr[pivot] && i<last)
i++;
while(arr[j]>arr[pivot])
j--;
if(i<j)
{
tmp=arr[i];
arr[i]=arr[j];