Introduction
Imagine having a messy deck of cards - that’s what unsorted data looks like in programming. Sorting is the process of arranging data in a specific order, whether it’s numerical (ascending or descending) or alphabetical. In this guide, we’ll learn how to bring order to chaos using C programming.
Understanding Bubble Sort
Bubble sort is one of the simplest sorting algorithms to understand. Think of it like arranging a line of students by height - you compare two students at a time and swap their positions if needed.
How Bubble Sort Works
Let’s start with a simple example:
#include <stdio.h>
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
= arr[j];
temp [j] = arr[j+1];
arr[j+1] = temp;
arr}
}
}
}
int main() {
int numbers[] = {64, 34, 25, 12, 22, 11, 90};
int n = sizeof(numbers)/sizeof(numbers[0]);
("Before sorting: ");
printffor (int i = 0; i < n; i++) {
("%d ", numbers[i]);
printf}
(numbers, n);
bubbleSort
("\nAfter sorting: ");
printffor (int i = 0; i < n; i++) {
("%d ", numbers[i]);
printf}
return 0;
}
Output:
Before sorting: 64 34 25 12 22 11 90
After sorting: 11 12 22 25 34 64 90
Working with Random Numbers
Here’s a practical example that generates and sorts random numbers:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main() {
int nums[10];
time_t t;
(time(&t)); // Initialize random number generator
srand
// Generate random numbers
for (int i = 0; i < 10; i++) {
[i] = (rand() % 99) + 1;
nums}
// Print original array
("Original numbers: ");
printffor (int i = 0; i < 10; i++) {
("%d ", nums[i]);
printf}
// Sort array
for (int outer = 0; outer < 9; outer++) {
int didSwap = 0;
for (int inner = outer; inner < 10; inner++) {
if (nums[inner] < nums[outer]) {
int temp = nums[inner];
[inner] = nums[outer];
nums[outer] = temp;
nums= 1;
didSwap }
}
if (didSwap == 0) break;
}
// Print sorted array
("\nSorted numbers: ");
printffor (int i = 0; i < 10; i++) {
("%d ", nums[i]);
printf}
return 0;
}
Output:
Original numbers: 20 79 22 83 36 97 95 81 57 77
Sorted numbers: 20 79 22 83 36 97 95 81 57 77
Real-World Application: Customer Database
Here’s a practical example showing how to sort customer records:
#include <stdio.h>
struct Customer {
int id;
float balance;
};
void sortCustomers(struct Customer customers[], int n) {
int i, j;
struct Customer temp;
for (i = 0; i < n-1; i++) {
for (j = 0; j < n-i-1; j++) {
if (customers[j].id > customers[j+1].id) {
= customers[j];
temp [j] = customers[j+1];
customers[j+1] = temp;
customers}
}
}
}
int main() {
struct Customer customers[] = {
{313, 150.50},
{202, 75.25},
{101, 225.75},
{405, 50.00},
{108, 125.50}
};
int n = 5;
("Before sorting:\n");
printffor (int i = 0; i < n; i++) {
("ID: %d, Balance: $%.2f\n",
printf[i].id, customers[i].balance);
customers}
(customers, n);
sortCustomers
("\nAfter sorting by ID:\n");
printffor (int i = 0; i < n; i++) {
("ID: %d, Balance: $%.2f\n",
printf[i].id, customers[i].balance);
customers}
return 0;
}
Output:
Before sorting:
ID: 313, Balance: $150.50
ID: 202, Balance: $75.25
ID: 101, Balance: $225.75
ID: 405, Balance: $50.00
ID: 108, Balance: $125.50
After sorting by ID:
ID: 101, Balance: $225.75
ID: 108, Balance: $125.50
ID: 202, Balance: $75.25
ID: 313, Balance: $150.50
ID: 405, Balance: $50.00
Your Turn!
Try implementing a bubble sort for strings. Here’s the challenge:
Write a program that sorts 5 names alphabetically.
Click to see solution
#include <stdio.h>
#include <string.h>
void sortStrings(char *names[], int n) {
int i, j;
char *temp;
for (i = 0; i < n-1; i++) {
for (j = 0; j < n-i-1; j++) {
if (strcmp(names[j], names[j+1]) > 0) {
= names[j];
temp [j] = names[j+1];
names[j+1] = temp;
names}
}
}
}
int main() {
char *names[] = {"John", "Alice", "Bob", "Carol", "David"};
int n = 5;
("Before sorting:\n");
printffor (int i = 0; i < n; i++) {
("%s\n", names[i]);
printf}
(names, n);
sortStrings
("\nAfter sorting:\n");
printffor (int i = 0; i < n; i++) {
("%s\n", names[i]);
printf}
return 0;
}
Quick Takeaways
- Always use a temporary variable when swapping values
- Bubble sort is perfect for learning and small datasets
- For large datasets, consider more efficient algorithms
- Sorting makes searching much faster
- Keep parallel arrays in sync when sorting
Frequently Asked Questions
Q: Why do we need a temporary variable when swapping? A: Without it, you’ll lose the original value during the swap. The temp variable stores one value while you make the swap.
Q: How can I sort in descending order? A: Change the comparison operator from ‘>’ to ‘<’ in the if condition.
Q: Is bubble sort efficient for large datasets? A: No, it’s best for small datasets or teaching purposes. For large datasets, use more advanced algorithms.
Q: Can I sort decimal numbers using bubble sort? A: Yes, just change the data type from int to float or double.
Q: How do I know if my sort worked correctly? A: Check if each element is less than or equal to the next element in the array.
References
Conclusion
Bubble sort is an excellent starting point for understanding sorting algorithms. While it may not be the most efficient method, its simplicity makes it perfect for learning. Remember to practice with the provided examples and try creating your own sorting programs!
Happy Coding! 🚀
You can connect with me at any one of the below:
Telegram Channel here: https://t.me/steveondata
LinkedIn Network here: https://www.linkedin.com/in/spsanderson/
Mastadon Social here: https://mstdn.social/@stevensanderson
RStats Network here: https://rstats.me/@spsanderson
GitHub Network here: https://github.com/spsanderson
Bluesky Network here: https://bsky.app/profile/spsanderson.com
My Book: Extending Excel with Python and R here: https://packt.link/oTyZJ
You.com Referral Link: https://you.com/join/EHSLDTL6