Experiment 13 – Search and Sort Algorithms
Aim
To implement searching algorithms (linear search and binary search) and sorting algorithms (bubble sort and selection sort) in C programming. Understand algorithm efficiency and time complexity. This experiment helps students learn fundamental algorithms, understand their implementations, and analyze their performance characteristics.
Through this experiment, students will learn to implement basic search and sort algorithms, understand when to use each algorithm, analyze time and space complexity, and recognize the importance of algorithm efficiency in programming.
Learning Outcomes
After completing this experiment, students will be able to:
- Implement linear search algorithm for unsorted arrays
- Implement binary search algorithm for sorted arrays
- Implement bubble sort algorithm for array sorting
- Implement selection sort algorithm for array sorting
- Understand time complexity: O(n) for linear search, O(log n) for binary search, O(n²) for bubble/selection sort
- Compare algorithm efficiency and choose appropriate algorithm
- Understand the relationship between sorting and searching efficiency
- Analyze algorithm performance and optimization opportunities
Algorithm
Detailed algorithms for each operation:
Linear Search Algorithm:
- Start from first element (index 0)
- Compare each element with search key
- If match found, return index
- If end of array reached, return -1 (not found)
- Time Complexity: O(n), Space: O(1)
Binary Search Algorithm:
- Requires sorted array
- Set left = 0, right = n-1
- While left <= right: calculate mid = (left + right) / 2
- If arr[mid] == key, return mid
- If key < arr[mid], search left half (right = mid - 1)
- If key > arr[mid], search right half (left = mid + 1)
- If not found, return -1
- Time Complexity: O(log n), Space: O(1)
Bubble Sort Algorithm:
- For each pass i from 0 to n-2
- Compare adjacent elements from 0 to n-i-2
- If arr[j] > arr[j+1], swap them
- Largest element "bubbles" to end after each pass
- Repeat until no swaps in a pass
- Time Complexity: O(n²), Space: O(1)
Selection Sort Algorithm:
- For each position i from 0 to n-2
- Find minimum element in unsorted portion (from i to n-1)
- Swap minimum with element at position i
- Move boundary of sorted portion
- Time Complexity: O(n²), Space: O(1)
Procedure
- Include
stdio.hheader file - For Linear Search:
- Traverse array from start to end
- Compare each element with search key
- Return index if found, -1 if not found
- For Binary Search (requires sorted array):
- Compare key with middle element
- If equal, return index
- If key < middle, search left half
- If key > middle, search right half
- Repeat until found or search space exhausted
- For Bubble Sort:
- Compare adjacent elements
- Swap if they are in wrong order
- Repeat for all elements
- Continue until no swaps needed
- For Selection Sort:
- Find minimum element in unsorted portion
- Swap with first element of unsorted portion
- Move boundary of sorted portion
Flowchart
Linear Search:
START
├─→ FOR i = 0 to n-1
│ │
│ ├─→ IF (arr[i] == key)
│ │ │
│ │ └─→ RETURN i
│ │
│ └─→ END FOR
│
└─→ RETURN -1
Binary Search:
START
├─→ left = 0, right = n-1
├─→ WHILE (left <= right)
│ │
│ ├─→ mid = (left + right) / 2
│ ├─→ IF (arr[mid] == key)
│ │ │
│ │ └─→ RETURN mid
│ │
│ ├─→ IF (key < arr[mid])
│ │ │
│ │ └─→ right = mid - 1
│ │
│ └─→ ELSE
│ │
│ └─→ left = mid + 1
│
└─→ RETURN -1
Bubble Sort:
START
├─→ FOR i = 0 to n-2
│ │
│ ├─→ FOR j = 0 to n-i-2
│ │ │
│ │ ├─→ IF (arr[j] > arr[j+1])
│ │ │ │
│ │ │ └─→ SWAP arr[j] and arr[j+1]
│ │ │
│ │ └─→ END FOR j
│ │
│ └─→ END FOR i
│
└─→ ENDProgram Code
#include <stdio.h>
// Linear Search
int linearSearch(int arr[], int n, int key) {
int i;
for (i = 0; i < n; i++) {
if (arr[i] == key) {
return i; // Return index if found
}
}
return -1; // Return -1 if not found
}
// Binary Search (requires sorted array)
int binarySearch(int arr[], int n, int key) {
int left = 0, right = n - 1, mid;
while (left <= right) {
mid = (left + right) / 2;
if (arr[mid] == key) {
return mid; // Found at index mid
}
if (key < arr[mid]) {
right = mid - 1; // Search left half
} else {
left = mid + 1; // Search right half
}
}
return -1; // Not found
}
// Bubble Sort
void bubbleSort(int arr[], int n) {
int i, j, temp;
for (i = 0; i < n - 1; i++) {
for (j = 0; j < n - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
// Swap elements
temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}
// Selection Sort
void selectionSort(int arr[], int n) {
int i, j, min_idx, temp;
for (i = 0; i < n - 1; i++) {
min_idx = i; // Assume first element is minimum
// Find minimum element in unsorted portion
for (j = i + 1; j < n; j++) {
if (arr[j] < arr[min_idx]) {
min_idx = j;
}
}
// Swap minimum with first element of unsorted portion
if (min_idx != i) {
temp = arr[i];
arr[i] = arr[min_idx];
arr[min_idx] = temp;
}
}
}
// Function to display array
void displayArray(int arr[], int n) {
int i;
for (i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
printf("\n");
}
int main() {
int arr[100], n, i, key, choice, index;
printf("Enter number of elements: ");
scanf("%d", &n);
printf("Enter %d elements:\n", n);
for (i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}
printf("\n1. Linear Search\n");
printf("2. Binary Search (array must be sorted)\n");
printf("3. Bubble Sort\n");
printf("4. Selection Sort\n");
printf("Enter your choice: ");
scanf("%d", &choice);
switch(choice) {
case 1:
printf("Enter element to search: ");
scanf("%d", &key);
index = linearSearch(arr, n, key);
if (index != -1) {
printf("Element %d found at index %d\n", key, index);
} else {
printf("Element %d not found in array.\n", key);
}
break;
case 2:
// Sort array first for binary search
bubbleSort(arr, n);
printf("Array sorted for binary search: ");
displayArray(arr, n);
printf("Enter element to search: ");
scanf("%d", &key);
index = binarySearch(arr, n, key);
if (index != -1) {
printf("Element %d found at index %d\n", key, index);
} else {
printf("Element %d not found in array.\n", key);
}
break;
case 3:
printf("Original array: ");
displayArray(arr, n);
bubbleSort(arr, n);
printf("Sorted array (Bubble Sort): ");
displayArray(arr, n);
break;
case 4:
printf("Original array: ");
displayArray(arr, n);
selectionSort(arr, n);
printf("Sorted array (Selection Sort): ");
displayArray(arr, n);
break;
default:
printf("Invalid choice!\n");
}
return 0;
}Sample Input and Output
Sample 1: Linear Search
Input:
Enter number of elements: 5 Enter 5 elements: 10 20 30 40 50 1. Linear Search 2. Binary Search (array must be sorted) 3. Bubble Sort 4. Selection Sort Enter your choice: 1 Enter element to search: 30
Output:
Element 30 found at index 2
Sample 2: Bubble Sort
Input:
Enter number of elements: 6 Enter 6 elements: 64 34 25 12 22 11 1. Linear Search 2. Binary Search (array must be sorted) 3. Bubble Sort 4. Selection Sort Enter your choice: 3
Output:
Original array: 64 34 25 12 22 11 Sorted array (Bubble Sort): 11 12 22 25 34 64
Sample 3: Binary Search
Input:
Enter number of elements: 7 Enter 7 elements: 45 12 78 34 56 23 67 1. Linear Search 2. Binary Search (array must be sorted) 3. Bubble Sort 4. Selection Sort Enter your choice: 2 Enter element to search: 56
Output:
Array sorted for binary search: 12 23 34 45 56 67 78 Element 56 found at index 4
Use Case / Real-world Relevance
Search and sort algorithms are fundamental to computer science and are used everywhere:
- Database Systems: Indexing, querying, and sorting records efficiently
- Search Engines: Finding and ranking search results
- E-commerce: Sorting products by price, rating, popularity
- Operating Systems: Process scheduling, file system organization
- Data Analysis: Organizing and searching through large datasets
- Gaming: Leaderboards, inventory sorting, search functionality
- Social Media: Sorting posts by date, relevance, popularity
- Financial Systems: Transaction sorting, account lookups
Understanding algorithm complexity (time and space) is crucial for writing efficient code. Linear search is O(n), binary search is O(log n), while bubble and selection sorts are O(n²). Choosing the right algorithm for the right situation is a key programming skill. These fundamental algorithms form the basis for understanding more advanced algorithms and data structures used in professional software development.
Viva Questions
Q1: What is the time complexity of linear search and when should we use it?
Linear search has O(n) time complexity in worst case (must check all elements). Use it for unsorted arrays or when array is small. Advantages: simple, works on unsorted data, no preprocessing needed. Disadvantages: slow for large arrays. For sorted arrays, binary search is much faster (O(log n)).
Q2: Why does binary search require a sorted array?
Binary search uses the sorted property to eliminate half of the search space at each step. By comparing with middle element, we know which half contains the key (if key < middle, it's in left half; if key > middle, it's in right half). This wouldn't work with unsorted data. Sorting takes O(n log n) time, so binary search is only beneficial if you search multiple times.
Q3: What is the difference between bubble sort and selection sort?
Bubble sort compares adjacent elements and swaps if out of order, "bubbling" largest to end. Selection sort finds minimum in unsorted portion and swaps with first unsorted element. Both are O(n²), but selection sort typically makes fewer swaps (O(n) swaps vs O(n²) swaps). Bubble sort can be optimized to detect if array is already sorted and stop early.
Q4: Can we improve bubble sort efficiency?
Yes, add a flag to detect if any swaps occurred in a pass. If no swaps, array is sorted, stop early. This gives O(n) best case (already sorted) instead of always O(n²). However, worst and average cases remain O(n²). For better performance, use quicksort (O(n log n) average) or mergesort (O(n log n) worst case).
Q5: What is stable sorting and are bubble/selection sorts stable?
Stable sort maintains relative order of equal elements. Bubble sort is stable (only swaps adjacent elements when out of order). Selection sort is not stable (swapping minimum with first unsorted can change order of equal elements). Stability matters when sorting by multiple criteria (e.g., sort by name, then by age - stable sort preserves name order for same ages).
Q6: When would you choose linear search over binary search?
Choose linear search when: array is unsorted and sorting isn't worth it (small array, single search), array is small (overhead of binary search not worth it), data structure doesn't support random access (linked list). For large sorted arrays with multiple searches, binary search is much better. Rule of thumb: if searching once on unsorted data, use linear; if searching multiple times, sort first then use binary.
Q7: What is the space complexity of these algorithms?
All algorithms have O(1) space complexity (constant extra space): linear search uses few variables, binary search uses left/right/mid variables, bubble and selection sorts use temp variable for swapping. They sort in-place without requiring additional arrays. This is efficient memory-wise, though time complexity varies significantly.
Q8: How would you modify binary search to find first/last occurrence of duplicate elements?
For first occurrence: when arr[mid] == key, don't return immediately. Check if mid-1 also equals key. If yes, search left half (right = mid - 1). For last occurrence: when arr[mid] == key, check if mid+1 equals key. If yes, search right half (left = mid + 1). Continue until you find the boundary where key starts/ends.
Related Links
🔹 Author: Dr. J. Siva Ramakrishna
🔹 Institution: Narayana Engineering College, Gudur
🔹 Last Updated: 9 January 2026