UNIT-4 Searching & Sorting
UNIT-4 Searching & Sorting
Again,
both the elements are not matching,
you move onto the next following element.
LINEAR SEARCH (CONT…)
Step 4: Next, search element 39 is compared with the
fourth element, which is 15.
return arr
end BubbleSort
BUBBLE SORT (CONT…)
How does Bubble Sort Work?
Let us understand the working of bubble sort with the
help of the following illustration:
First Pass:
The largest element is placed in its correct position,
i.e., the end of the array.
BUBBLE SORT (CONT…)
Second Pass:
Place the second largest element at correct
position
BUBBLE SORT (CONT…)
Third Pass:
Place the remaining two elements at their
correct positions.
BUBBLE SORT (CONT…)
#include<stdio.h>
void main()
{
int i,j,temp,n,a[10];
printf("Enter Elements in Array \n");
for(i=0;i<10;i++)
{
scanf("%d",&a[i]);
}
for(i=0;i<10;i++)
{
BUBBLE SORT (CONT…)
for(j=0;j<10-i;j++)
{
if(a[j]>a[j+1])
{
temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
}
}
}
printf("Sorted Array is: \n");
for(i=0;i<10;i++)
printf("%d \t",a[i]);
}
INSERTION SORT
Insertion sort is an algorithm used to sort a collection
of elements in ascending or descending order.
First Pass:
INSERTION SORT (CONT…)
Second Pass:
INSERTION SORT (CONT…)
Third Pass:
INSERTION SORT (CONT…)
Fourth Pass:
INSERTION SORT (CONT…)
INSERTION SORT (CONT…)
INSERTION SORT (CONT…)
Program:
#include <stdio.h>
void main()
{
int n, i, j, temp;
int arr[64];
First Pass:
For the first position in the sorted array, the whole
array is traversed from index 0 to 4 sequentially.
#include <stdio.h>
void main()
{
int array[100], n, i, j, min, t;
It is an unstable sorting
2 It is a stable sorting algorithm.
algorithm.