Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
92 views

Binary Search, Bubble Sort, Insertion Sort

The document describes two sorting algorithms: 1) Binary search, which searches for a target element in a sorted array by repeatedly dividing the search interval in half. It compares the target to the middle element of the array and repeats the search in either the left or right half. 2) Bubble sort, which iterates through an array and compares adjacent elements, swapping them if they are out of order. It repeats this process until the array is fully sorted. The example shows bubble sorting an array of 10 integers into ascending order.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
92 views

Binary Search, Bubble Sort, Insertion Sort

The document describes two sorting algorithms: 1) Binary search, which searches for a target element in a sorted array by repeatedly dividing the search interval in half. It compares the target to the middle element of the array and repeats the search in either the left or right half. 2) Bubble sort, which iterates through an array and compares adjacent elements, swapping them if they are out of order. It repeats this process until the array is fully sorted. The example shows bubble sorting an array of 10 integers into ascending order.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 3

Binary Search

#include <stdio.h>
int main(void) {
int mid,first,last,n,a[100],k,i;
printf("\n enter the no of elements") ;
scanf("%d",&n);
printf("\n enter the values");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
printf("\n enter the element to be searched");
scanf("%d",&k);
first=0;
last=n-1;
mid=(first+last)/2;
while(first<=last)
{
if(a[mid]<k)
first=mid+1;
else if(a[mid]==k)
{
printf("%d element is in middle",k);
break;
}
else
last =mid-1;
mid=(first+last)/2;
}
return 0;
}

Bubble sort

#include<stdio.h>
int main()
{
int i,j,temp;
int a[10]={10,9,7,101,23,44,12,78,34,25};
for(i=0;i<10;i++)
{
for(j=i+1;j<10;j++)
{
if(a[i]>a[j])
{
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}
}
printf("\n sorted elements are:");
for(i=0;i<10;i++)
{
printf("%d\t",a[i]);
}
return 0;
}

You might also like