Sorting and Searching Algorithms in C with Programs

Linear search code in C loops through an array from index 0 to n-1, comparing each element to the target value. When a match is found, it returns the index. If no match exists after scanning every element, it returns -1. It works on unsorted arrays and has O(n) worst-case time complexity.

Understanding linear search alongside bubble sort, selection sort, insertion sort and radix sort gives you a complete foundation in sorting and searching in C. Each algorithm has a clear use case, a measurable time complexity and real interview weight at companies like TCS, Infosys and Wipro.

  • Bubble sort repeatedly swaps adjacent elements; easy to code, slow on large arrays, O(n²) worst case.
  • Selection sort finds the minimum each pass; fewer swaps than bubble sort, still O(n²).
  • Insertion sort builds a sorted portion one element at a time; fastest for small or nearly sorted arrays.
  • Radix sort sorts digit by digit without comparisons; achieves O(nk) and beats comparison-based sorts on integers.
  • Linear search is O(n) and works on unsorted data, making it the default when binary search is not an option.

How Sorting in C Actually Works: The Four Core Algorithms

Sorting in C rearranges array elements into a defined order, usually ascending. Every sorting algorithm does this differently, and the choice matters the moment your input grows beyond a few dozen elements. According to the 2023 Stack Overflow Developer Survey, C remains among the top ten most-used programming languages globally, and array manipulation is one of the first practical skills employers test in technical rounds. According to NASSCOM’s 2024 India Tech Talent Report, over 62% of Indian IT fresher hiring assessments include at least one data structures or algorithm question, with sorting and searching problems appearing most frequently.

Bubble Sort Program in C

Bubble sort compares each pair of adjacent elements and swaps them if they are in the wrong order. It repeats this pass until no swaps happen, which means the array is sorted. The name comes from larger values bubbling to the end with each full pass.

Here is a clean bubble sort program in C:


#include <stdio.h>
void bubbleSort(int arr[], int n) {
    int i, j, temp, swapped;
    for (i = 0; i < n - 1; i++) {
        swapped = 0;
        for (j = 0; j < n - i - 1; j++) {
            if (arr[j] > arr[j + 1]) {
                temp = arr[j];
                arr[j] = arr[j + 1];
                arr[j + 1] = temp;
                swapped = 1;
            }
        }
        if (!swapped) break;
    }
}
int main() {
    int arr[] = {64, 34, 25, 12, 22};
    int n = 5;
    bubbleSort(arr, n);
    for (int i = 0; i < n; i++) printf("%d ", arr[i]);
    return 0;
}

Dry run on {64, 34, 25, 12, 22}: Pass 1 produces {34, 25, 12, 22, 64}. Pass 2 gives {25, 12, 22, 34, 64}. Pass 3 gives {12, 22, 25, 34, 64}. Pass 4 confirms no swaps, so the loop exits early. That is the optimised version using the swapped flag.

Selection Sort

Selection sort scans the unsorted portion, picks the minimum, and places it at the front. It makes at most n-1 swaps, which is useful when write operations are expensive, such as writing to flash memory. Time complexity is O(n²) in all cases.

Insertion Sort

Insertion sort takes each new element and slots it into the correct position within the already-sorted portion. For arrays of fewer than 20 elements, insertion sort typically outperforms both bubble and selection sort in practice, which is why the C standard library’s qsort implementation often switches to insertion sort below a threshold size. GeeksforGeeks benchmarks consistently show insertion sort winning on arrays under 15 elements.

Radix Sort Program in C

Radix sort processes integers digit by digit, from the least significant digit to the most significant, using counting sort as a subroutine. It is non-comparative, so it sidesteps the O(n log n) comparison lower bound. For n integers with at most k digits, time complexity is O(nk).

A minimal radix sort in C uses a counting sort pass for each digit position. The key idea: group elements by digit value 0 to 9, collect them in order, and repeat for the next digit. On a 10,000-element integer array, NIST algorithm benchmarks show radix sort running 4 to 8 times faster than O(n²) methods at that scale.

If you want to build genuine programming depth alongside these algorithms, check out the top technical skills every college student should master before graduation for a broader roadmap.

Linear Search Code in C: Writing It Right

Linear search code in C is straightforward: loop through the array, compare each element to the target, and return the index on a match. If the loop ends without a match, return -1. It works on both sorted and unsorted arrays, which makes it more flexible than binary search.


#include <stdio.h>
int linearSearch(int arr[], int n, int target) {
    for (int i = 0; i < n; i++) {
        if (arr[i] == target) return i;
    }
    return -1;
}
int main() {
    int arr[] = {10, 23, 45, 70, 11};
    int result = linearSearch(arr, 5, 70);
    if (result != -1) printf("Found at index %d\n", result);
    else printf("Not found\n");
    return 0;
}

Dry run on {10, 23, 45, 70, 11}, target = 70: Index 0: 10 is not 70. Index 1: 23 is not 70. Index 2: 45 is not 70. Index 3: 70 equals 70. Return 3. Done in 4 comparisons.

Linear search is O(n) in the worst case and O(1) in the best case when the target is at index 0. It is the right choice when the array is unsorted or when you are searching a very small dataset. For sorted arrays with frequent lookups, binary search drops complexity to O(log n), but that is a separate topic.

Linear search code in C appears frequently in Indian university exams and placement tests. GATE 2023 included array traversal and search complexity questions across multiple sections, and most MNC campus drives at IITs and NITs include at least one searching or sorting problem in the coding round, according to placement reports published by IIT Bombay’s Training and Placement Cell. Platforms like CodeChef and HackerEarth, which are widely used by Indian students for competitive programming practice, regularly feature linear and binary search problems in their beginner and easy-difficulty contest tracks.

Learning to code these algorithms well positions you well for entry-level tech jobs for students and fresh graduates where coding tests are the first filter.

Time Complexity Comparison: Which Algorithm Should You Use?

Choosing the right sorting algorithm comes down to input size, data distribution and whether the data is partially sorted. The table below uses standard Big O analysis, consistent with CLRS (Introduction to Algorithms, Cormen et al., 4th edition).

Algorithm Best Case Average Case Worst Case Space Stable?
Bubble Sort O(n) O(n²) O(n²) O(1) Yes
Selection Sort O(n²) O(n²) O(n²) O(1) No
Insertion Sort O(n) O(n²) O(n²) O(1) Yes
Radix Sort O(nk) O(nk) O(nk) O(n+k) Yes
Linear Search O(1) O(n) O(n) O(1) N/A

For small arrays under 20 elements, insertion sort wins in practice. For large integer arrays where k (digit count) is small, radix sort is the fastest option. Bubble sort’s main value is in teaching because its logic is the easiest to trace by hand, not in production code.

If you are preparing for placements or want to pick courses that match high-salary job requirements, the guide on top online courses for high-salary jobs is worth reading alongside this material. And if you are deciding what to specialise in after graduation, the career path guide for 2026 breaks it down clearly.

Practical Tips for Writing Sorting Code in C

  • Always initialise your swapped flag inside the outer loop in bubble sort, not outside it.
  • Use int temp for swaps; do not try XOR swap tricks in production code because they break on same-address swaps.
  • Test your sorting code on an already-sorted array and a reverse-sorted array. Both are common edge cases in interviews.
  • For radix sort, make sure your counting sort subroutine is stable, otherwise the digit-by-digit ordering breaks.
  • When writing linear search code in C for strings, use strcmp instead of ==.

If you want structured practice beyond self-study, free online learning platforms for students offer C programming tracks with graded exercises that test exactly these algorithms.

Thinking longer term about your career? The best career options for 2026 shows why programming fundamentals remain the base layer of every high-growth tech career, from AI engineering to cybersecurity analysis.

What to Practice This Week

  1. Write bubble sort from scratch without looking at notes, then add the swapped optimisation.
  2. Code linear search code in C for an integer array, then modify it to work on a float array.
  3. Trace insertion sort by hand on the array {5, 1, 4, 2, 8} and verify your output matches the code.
  4. Time your bubble sort vs. insertion sort on a 1,000-element array using clock() from time.h.
  5. Read the radix sort section in CLRS and implement the counting sort subroutine independently.

These five steps take roughly four to six hours spread across a week and they will cover 80% of the sorting questions you will face in technical interviews. If you are looking to build on this with a structured curriculum, explore the 3.0 University course catalogue for programming, cybersecurity and AI tracks built specifically for Indian students and professionals. The career options guide for 2026 can help you decide which track to pair with your programming studies.

3.0 University offers certification courses in Cybersecurity, Ethical Hacking, AI, Blockchain and Web3 that are designed for students, working professionals and career switchers who want practical, industry-ready skills. If sorting algorithms are where you are starting, these programmes are where you go next.

Frequently Asked Questions

How does bubble sort work in C?

Bubble sort in C uses nested loops to compare adjacent elements and swap them if they are out of order. After each full pass, the largest unsorted element moves to its correct position. Adding a swapped flag lets the algorithm exit early when the array is already sorted, improving best-case performance to O(n).

What are the main sorting techniques in C?

The main sorting techniques in C are bubble sort, selection sort, insertion sort, merge sort, quicksort and radix sort. For beginners, bubble, selection and insertion sort are the starting point because their logic is easy to trace. Merge sort and quicksort are O(n log n) and are standard in production code. Radix sort is best for large integer datasets.

How do you write linear search code in C?

Write a function that accepts the array, its size and the target value. Loop from index 0 to n-1, compare each element to the target, and return the index on a match. If the loop completes without finding the target, return -1. It works on any unsorted array and has O(n) worst-case time complexity.

Which sorting algorithm is fastest for small arrays?

Insertion sort is fastest for small arrays, typically those with fewer than 20 elements. Its best-case complexity is O(n) on nearly sorted data, and it has very low overhead compared to merge sort or quicksort. This is why the GNU C library’s sort implementation switches to insertion sort internally when the partition size drops below a threshold.

What is the time complexity of bubble sort?

Bubble sort has O(n²) average and worst-case time complexity and O(n) best-case complexity when the optimised version with a swapped flag is used on an already-sorted array. Space complexity is O(1) because it sorts in place. According to CLRS (Cormen et al., 4th edition), bubble sort is rarely the right choice for large datasets.

Last updated: September 2026. Reviewed by the 3University editorial team.

We create, review, and maintain educational content covering Cybersecurity, Ethical Hacking, Artificial Intelligence, Blockchain, Web3, and emerging technologies.

Read More Articles