Searching and Sorting Lab Programs[1]
Searching and Sorting Lab Programs[1]
a) Linear Search
#include <stdio.h>
// Function prototype
int main()
scanf("%d", &n);
scanf("%d", &a[i]);
scanf("%d", &item);
if (loc == -1)
printf("Search unsuccessful\n");
else
return 0;
{
int i;
if (a[i] == item)
return i;
return -1;
// Function prototype
int main()
scanf("%d", &n);
scanf("%d", &a[i]);
scanf("%d", &item);
if (loc == -1)
printf("Search unsuccessful\n");
else
return 0;
if(n<0)
if(a[n-1]==item)
else
b) Binary Search
#include <stdio.h>
// Function prototype
int main() {
scanf("%d", &n);
scanf("%d", &a[i]);
printf("Enter item to search:\n");
scanf("%d", &item);
if (pos != -1)
else
return 0;
if (item == a[mid])
return mid;
beg = mid + 1;
else
end = mid - 1;
return -1;
int main() {
scanf("%d", &n);
scanf("%d", &a[i]);
scanf("%d", &item);
if (loc == -1)
else
return 0;
int mid;
return -1;
return mid;
else
a) Selection sort
#include <stdio.h>
int i, j, small;
for (i = 0; i < n-1; i++) // One by one move boundary of unsorted subarray
small = j;
if(small!=i)
{
arr[small] = arr[i];
arr[i] = temp;
int main()
scanf("%d", &n);
scanf("%d", &arr[i]);
}
// call the function SelectionSort
SelectionSort(arr, n);
return 0;
b) Bubble sort.
#include <stdio.h>
int i, j, temp;
temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
int main()
scanf("%d", &n);
scanf("%d", &arr[i]);
bubbleSort(arr, n);
return 0;
}
Write a C program to implement insertion sort
#include <stdio.h>
int main() {
int i, j, key;
key = a[i];
j = i - 1;
a[j + 1] = a[j];
j--;
a[j + 1] = key;
return 0;