Searching and Sorting Codes

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 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

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy