A Beginner’s Guide to Sorting and Alphabetizing Data in C Programming

Learn how to implement bubble sort and alphabetize data in C programming with our comprehensive guide. Perfect for beginners with step-by-step examples and practical code.
code
c
Author

Steven P. Sanderson II, MPH

Published

February 26, 2025

Keywords

Programming, C programming bubble sort, sorting algorithms in C, C array sorting, bubble sort tutorial, C programming sorting examples, how to implement bubble sort, C sorting techniques, sorting data structures C, bubble sort optimization, C programming arrays, how to sort strings alphabetically in C programming, optimize bubble sort performance in C, sorting customer data using bubble sort C, bubble sort vs other sorting algorithms C, step by step bubble sort implementation C

Author’s Note

Hey there! 👋

I want to be completely transparent with you - I’m learning and growing as a programmer too, just like many of you. While writing this series on C programming, I’m discovering new techniques and approaches every day. That’s the beauty of programming - there’s always something new to learn!

If you spot any mistakes in my code examples or know of a more efficient way to implement these sorting algorithms, please don’t hesitate to share in the comments. Your feedback not only helps me improve but also benefits the entire community of learners.

Remember: there’s often more than one way to solve a programming problem. The solutions I’ve presented are meant to be clear and beginner-friendly, but they might not always be the most optimized. I encourage you to experiment with different approaches and share your discoveries.

Let’s learn together! 💻


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
                temp = arr[j];
                arr[j] = arr[j+1];
                arr[j+1] = temp;
            }
        }
    }
}

int main() {
    int numbers[] = {64, 34, 25, 12, 22, 11, 90};
    int n = sizeof(numbers)/sizeof(numbers[0]);
    
    printf("Before sorting: ");
    for (int i = 0; i < n; i++) {
        printf("%d ", numbers[i]);
    }
    
    bubbleSort(numbers, n);
    
    printf("\nAfter sorting: ");
    for (int i = 0; i < n; i++) {
        printf("%d ", numbers[i]);
    }
    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;
    srand(time(&t)); // Initialize random number generator
    
    // Generate random numbers
    for (int i = 0; i < 10; i++) {
        nums[i] = (rand() % 99) + 1;
    }
    
    // Print original array
    printf("Original numbers: ");
    for (int i = 0; i < 10; i++) {
        printf("%d ", nums[i]);
    }
    
    // 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];
                nums[inner] = nums[outer];
                nums[outer] = temp;
                didSwap = 1;
            }
        }
        if (didSwap == 0) break;
    }
    
    // Print sorted array
    printf("\nSorted numbers: ");
    for (int i = 0; i < 10; i++) {
        printf("%d ", nums[i]);
    }
    
    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) {
                temp = customers[j];
                customers[j] = customers[j+1];
                customers[j+1] = temp;
            }
        }
    }
}

int main() {
    struct Customer customers[] = {
        {313, 150.50},
        {202, 75.25},
        {101, 225.75},
        {405, 50.00},
        {108, 125.50}
    };
    int n = 5;
    
    printf("Before sorting:\n");
    for (int i = 0; i < n; i++) {
        printf("ID: %d, Balance: $%.2f\n", 
               customers[i].id, customers[i].balance);
    }
    
    sortCustomers(customers, n);
    
    printf("\nAfter sorting by ID:\n");
    for (int i = 0; i < n; i++) {
        printf("ID: %d, Balance: $%.2f\n", 
               customers[i].id, customers[i].balance);
    }
    
    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) {
                temp = names[j];
                names[j] = names[j+1];
                names[j+1] = temp;
            }
        }
    }
}

int main() {
    char *names[] = {"John", "Alice", "Bob", "Carol", "David"};
    int n = 5;
    
    printf("Before sorting:\n");
    for (int i = 0; i < n; i++) {
        printf("%s\n", names[i]);
    }
    
    sortStrings(names, n);
    
    printf("\nAfter sorting:\n");
    for (int i = 0; i < n; i++) {
        printf("%s\n", names[i]);
    }
    
    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

  1. 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.

  2. Q: How can I sort in descending order? A: Change the comparison operator from ‘>’ to ‘<’ in the if condition.

  3. 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.

  4. Q: Can I sort decimal numbers using bubble sort? A: Yes, just change the data type from int to float or double.

  5. 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

  1. GeeksforGeeks - Bubble Sort
  2. Programiz - C Programming Examples
  3. C Programming - GNU Documentation
  4. TutorialsPoint - C Arrays

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! 🚀

Sorting in C

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