0% found this document useful (0 votes)
11 views

Searching and Sorting Codes

Uploaded by

chnsivaprasad39
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views

Searching and Sorting Codes

Uploaded by

chnsivaprasad39
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 3

Searching and sorting programs

Binary search

#include <stdio.h>
int main()
{
int c, first, last, middle, n, search, array[100];

printf("Enter number of elements\n");


scanf("%d", &n);

printf("Enter %d integers\n", n);

for (c = 0; c < n; c++)


scanf("%d", &array[c]);

printf("Enter value to find\n");


scanf("%d", &search);

first = 0;
last = n - 1;
middle = (first+last)/2;

while (first <= last) {


if (array[middle] < search)
first = middle + 1;
else if (array[middle] == search) {
printf("%d found at location %d.\n", search, middle+1);
break;
}
else
last = middle - 1;

middle = (first + last)/2;


}
if (first > last)
printf("Not found! %d isn't present in the list.\n", search);

return 0;
}

2.Linear search
#include <stdio.h>
int main()
{

int num;

int i, key, element_found = 0;

printf("Enter number of elements you would like to take as input: ");

scanf("%d", &num);

int arr[num];

printf("\nEnter all the elements of your choice:");

for (i = 0; i < num; i++)

scanf("%d", &arr[i]);

printf("\nEnter the key element that you would like to be searched: ");

scanf("%d", &key);

for (i = 0; i < num ; i++)

if (key == arr[i] )

element_found = 1;

break;

if (element_found == 1)

printf("we got the element at index %d",i+1);

else
printf("we haven’t got element at any index in the array\n");

3.bubble sort:
#include <stdio.h>
int main(){
int a[50], n, i, j, temp;
printf("Please Enter the Number of Elements : ");
scanf("%d", &n);
for(i = 0; i < n; i++)
scanf("%d", &a[i]);
for(i = 0; i < n - 1; i++){
for(j = 0; j < n - i - 1; j++){
if(a[j] > a[j + 1]){
temp = a[j];
a[j] = a[j + 1];
a[j + 1] = temp;
}
}
}
printf("Array after implementing bubble sort: ");
for(i = 0; i < n; i++){
printf("%d ", a[i]);
}
return 0;
}

You might also like