📊 Comprehensive Applications of C Language Arrays: Detailed Explanation of Sorting and Searching
Author: IoT Smart Academy
🧠 1. Why Learn Sorting and Searching?
In previous chapters, we can store a lot of data, but the order is random. For example:
int score[5] = {75, 90, 60, 85, 80};
If we want to find the highest score, the lowest score, or output in ascending order, we need to use sorting (Sort); if we want to check if a student’s score exists, we need to use searching (Search).
These two types of algorithms are the core of computer thinking!🔥
✨ 2. Concept of Sorting
The purpose of sorting:
To rearrange a set of unordered data according to certain rules (ascending/descending).
Common sorting algorithms include:
- Bubble Sort — the most classic and easiest to understand;
- Selection Sort — slightly more efficient;
- Insertion Sort — suitable for data that is mostly ordered.
In this section, we will focus on the first two.
🌟 Example 1: Bubble Sort
📋 Principle Explanation (Simple Understanding)
The name Bubble Sort comes from — “smaller numbers float up like bubbles.”
Each time we compare two adjacent elements, if the one in front is larger than the one behind, we swap them. At the end of each round, the maximum value will ‘float’ to the end.
✅ Complete Code (Ascending Sort)
#include <stdio.h>
int main() {
int a[5];
int i, j, temp;
printf("Please enter 5 integers:\n");
for (i = 0; i < 5; i++)
scanf("%d", &a[i]);
// Bubble Sort
for (i = 0; i < 4; i++) { // Outer loop controls the number of rounds
for (j = 0; j < 4 - i; j++) { // Inner loop controls the number of comparisons
if (a[j] > a[j + 1]) { // If the front > back, then swap
temp = a[j];
a[j] = a[j + 1];
a[j + 1] = temp;
}
}
}
printf("Ascending order result:\n");
for (i = 0; i < 5; i++)
printf("%d ", a[i]);
printf("\n");
return 0;
}
🧩 Example Output
Please enter 5 integers:
75 90 60 85 80
Ascending order result:
60 75 80 85 90
📍 Algorithm Characteristics:
- Simple and easy to understand, but less efficient (suitable for teaching beginners);
- The nested loop structure is best for training “logical hierarchical thinking”.
🌟 Example 2: Selection Sort
📋 Principle Explanation
In each round, find the smallest element and place it in the appropriate position at the front.
Simple understanding:
“Each time, pick the smallest from the unsorted part and place it at the front.”
✅ Complete Code
#include <stdio.h>
int main() {
int a[5], i, j, min, temp;
printf("Please enter 5 integers:\n");
for (i = 0; i < 5; i++)
scanf("%d", &a[i]);
for (i = 0; i < 4; i++) {
min = i; // Assume the minimum is the current position
for (j = i + 1; j < 5; j++) {
if (a[j] < a[min])
min = j;
}
if (min != i) {
temp = a[i];
a[i] = a[min];
a[min] = temp;
}
}
printf("Selection sort result:\n");
for (i = 0; i < 5; i++)
printf("%d ", a[i]);
printf("\n");
return 0;
}
🧩 Example Output
Please enter 5 integers:
90 70 85 60 75
Selection sort result:
60 70 75 85 90
📍 Algorithm Characteristics:
- Each outer loop determines one position;
- Does not require as many swaps as bubble sort;
- Same time complexity, but with a smaller constant factor.
🕵️ 3. Searching Algorithms (Search)
When we have ordered or unordered arrays, we may need to check if a certain data exists.
Common methods include:
- Sequential Search
- Binary Search — requires data to be sorted.
🌟 Example 3: Sequential Search (The Simplest)
📋 Principle Explanation
Compare sequentially from the beginning to the end until the target is found or the end is reached.
✅ Complete Code
#include <stdio.h>
int main() {
int a[6] = {50, 60, 70, 80, 90, 100};
int x, i, found = 0;
printf("Please enter the number to search for:");
scanf("%d", &x);
for (i = 0; i < 6; i++) {
if (a[i] == x) {
printf("Found %d at position %d.\n", x, i + 1);
found = 1;
break;
}
}
if (!found)
printf("Number not found.\n");
return 0;
}
🧩 Example Output
Please enter the number to search for: 80
Found 80 at position 4.
📍 Advantages and Disadvantages:
- Simple structure;
- But less efficient when the data volume is large.
🌟 Example 4: Binary Search
📋 Principle Explanation
Prerequisite: The array must be sorted. The basic idea is “divide and conquer”:
Each time take the middle value and compare it with the target.
- If the target is less than the middle value → search on the left;
- If the target is greater than the middle value → search on the right;
- If equal, then found.
✅ Complete Code
#include <stdio.h>
int main() {
int a[10] = {10, 20, 30, 40, 50, 60, 70, 80, 90, 100};
int left = 0, right = 9, mid, x, found = 0;
printf("Please enter the number to search for:");
scanf("%d", &x);
while (left <= right) {
mid = (left + right) / 2;
if (a[mid] == x) {
printf("Found %d at position %d.\n", x, mid + 1);
found = 1;
break;
} else if (a[mid] > x)
right = mid - 1;
else
left = mid + 1;
}
if (!found)
printf("Number not found.\n");
return 0;
}
🧩 Example Output
Please enter the number to search for: 70
Found 70 at position 7.
📍 Algorithm Efficiency:
- Each time reduces the search range by half;
- Fast search speed (O(log n));
- Widely used in practical applications, such as database indexing, IoT data indexing.
🔧 4. Comprehensive Exercises
1️⃣ Input 10 temperature data, use bubble sort to output in ascending order. 2️⃣ Input 5 sensor IDs and signal strengths, use selection sort to sort by strength from high to low. 3️⃣ Perform binary search on the sorted array and output the index position of the target data. 4️⃣ Write a program that inputs 10 integers, sorts them, and then searches for an input value.
👉 These exercises will help students truly master the logic of “sorting + searching” algorithms.
✅ 5. Summary
| Content | Method | Characteristics |
|---|---|---|
| Sorting | Bubble Sort | Simple and easy to understand, suitable for teaching |
| Sorting | Selection Sort | Fewer swaps, slightly faster |
| Searching | Sequential Search | Can be used for unordered data |
| Searching | Binary Search | Efficient, but requires ordered data |
📌 Programming Motto:
“Sort first, then search; logic is clear; nested loops, be careful.”
🔜 Next Article Preview
📘 Comprehensive Practical Training in C Language: From Grade Management System to IoT Data Analysis
- Arrays + Loops + Conditions Comprehensive Practice
- Implementation: Input student information → Sort → Query → Calculate average score
- Extension: Sensor data storage and anomaly detection
📚 IoT Smart Academy
A vocational programming learning platform for IoT, 10 minutes a day, easily master C language from code to projects!