DS Lab Exercise 1
DS Lab Exercise 1
Searching Techniques
Program 2: Implementing Linear Search
#include<stdio.h>
int main()
{
int a[100];
int n,i,x;
// Getting the value of the element to search for within the array
printf("\nEnter the Number to search: ");
scanf("%d",&x);
if (array[mid] == x)
return mid;
if (array[mid] < x)
low = mid + 1;
else
high = mid - 1;
}
return -1;
}
int main(void)
{
int a[20],n,x,i;
Sort(a,n);
printf("\nSorted Array - ");
for(i=0;i<n;++i)
{
printf("%d ",a[i]);
}
return 0;
}
Output:
How many elements?8
Enter 8 array elements:
14
16
10
5
78
92
63
48
Enter element to search: 16
Sorted Array - 5 10 14 16 48 63 78 92
Element is found at index 3
------------------------------------------------------------------------------
Sorting Techniques
Program 4: Implementing Bubble Sort
#include <stdio.h>
// Function to perform the Bubble Sort Technique
void bubbleSort(int arr[], int n)
{
int i, j, temp;
int swapped;
// Outer loop for each pass
for (i = 0; i < n - 1; i++)
{
swapped = 0; // Track if any swaps are made
return 0;
}
------------------------------------------------------------------------------
Program 5: Implementing Selection Sort
#include <stdio.h>
// Function to implement the Selection Sort Technique
void selectionSort(int arr[], int n)
{
int i, j, minIndex, temp;
// Step 3: Swap the found minimum element with the first element of the
unsorted part
if (minIndex != i)
{
temp = arr[i];
arr[i] = arr[minIndex];
arr[minIndex] = temp;
}
int arr[n];
return 0;
}
Input:
Enter the number of elements: 10
Enter 10 elements:
56
12
48
79
90
64
37
10
5
29
Output:
Array after iteration 1: 12 56 48 79 90 64 37 10 5 29
Array after iteration 2: 12 48 56 79 90 64 37 10 5 29
Array after iteration 3: 12 48 56 79 90 64 37 10 5 29
Array after iteration 4: 12 48 56 79 90 64 37 10 5 29
Array after iteration 5: 12 48 56 64 79 90 37 10 5 29
Array after iteration 6: 12 37 48 56 64 79 90 10 5 29
Array after iteration 7: 10 12 37 48 56 64 79 90 5 29
Array after iteration 8: 5 10 12 37 48 56 64 79 90 29
Array after iteration 9: 5 10 12 29 37 48 56 64 79 90
Sorted array:
5 10 12 29 37 48 56 64 79 90
------------------------------------------------------------------------------