C Program To Sort The Elements Of An Array In Ascending Order
Sorting an array is a fundamental operation in computer science, crucial for organizing data efficiently. In this article, you will learn how to implement a simple C program to sort the elements of an array in ascending order.
Problem Statement
Often, data is collected or generated in an unsorted manner, making it challenging to perform operations like searching, finding minimum/maximum values, or presenting information clearly. For instance, a list of student scores might be entered randomly, but for analysis, it's essential to view them from lowest to highest. The problem is to arrange these unsorted elements into a specific order, typically ascending or descending.
Example
Consider an array of integers: [5, 2, 8, 1, 9].
After sorting in ascending order, the array should become: [1, 2, 5, 8, 9].
Background & Knowledge Prerequisites
To understand this article, readers should have a basic grasp of:
- C Language Fundamentals: Variables, data types, operators.
- Arrays: Declaring, initializing, and accessing elements.
- Loops:
forloops for iteration. - Conditional Statements:
ifstatements for comparison.
No special libraries or complex setups are required beyond a standard C compiler (like GCC).
Use Cases or Case Studies
Sorting algorithms are ubiquitous in various applications:
- Database Management: Arranging query results, indexing data for faster retrieval.
- Search Engines: Presenting search results by relevance or date.
- Graphical Applications: Rendering objects based on their depth (z-buffering).
- Data Analysis: Organizing datasets to find patterns, calculate statistics like median, or identify outliers.
- Operating Systems: Scheduling processes by priority or arrival time.
Solution Approaches
There are numerous algorithms to sort an array, each with its own advantages and complexities. Some common ones include Bubble Sort, Selection Sort, Insertion Sort, Merge Sort, and Quick Sort. For simplicity and ease of understanding, we will focus on Bubble Sort.
Bubble Sort
Bubble Sort is a straightforward sorting algorithm that repeatedly steps through the list, compares adjacent elements, and swaps them if they are in the wrong order. This process is repeated until no swaps are needed, indicating that the list is sorted. It gets its name because smaller elements "bubble" to the top (or beginning) of the list with each pass.
One-line Summary
Compares adjacent elements and swaps them if they are in the wrong order, repeatedly passing through the list until sorted.Code Example
// Array Sorting using Bubble Sort
#include <stdio.h>
int main() {
int arr[] = {64, 34, 25, 12, 22, 11, 90};
int n = sizeof(arr) / sizeof(arr[0]);
int i, j, temp;
printf("Original array: ");
for (i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
printf("\\n");
// Bubble Sort algorithm
// Outer loop for passes
for (i = 0; i < n - 1; i++) {
// Inner loop for comparisons and swaps in each pass
for (j = 0; j < n - i - 1; j++) {
// Compare adjacent elements
if (arr[j] > arr[j + 1]) {
// Swap if the current element is greater than the next
temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
printf("Sorted array in ascending order: ");
for (i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
printf("\\n");
return 0;
}
Sample Output
Original array: 64 34 25 12 22 11 90
Sorted array in ascending order: 11 12 22 25 34 64 90
Stepwise Explanation
- Initialization:
- An integer array
arris declared and initialized with unsorted values.
- An integer array
n calculates the number of elements in the array.i, j, and temp are declared for loop counters and temporary storage during swaps.- Display Original Array: The program first prints the elements of the
arras they are, before sorting, for comparison. - Outer Loop (
for (i = 0; i < n - 1; i++)):- This loop controls the number of passes through the array. For an array of
nelements,n-1passes are sufficient because in each pass, at least one element bubbles to its correct position. Afteripasses, the lastielements are guaranteed to be in their sorted positions.
- This loop controls the number of passes through the array. For an array of
- Inner Loop (
for (j = 0; j < n - i - 1; j++)):- This loop performs the comparisons and swaps within each pass.
n - i - 1 ensures that the loop only goes up to the unsorted part of the array. As i increases (more passes are completed), the n - i - 1 limit decreases, meaning fewer comparisons are needed in subsequent passes since the largest elements are already at the end.- Comparison and Swap (
if (arr[j] > arr[j + 1])):- Inside the inner loop,
arr[j]is compared with its adjacent elementarr[j + 1].
- Inside the inner loop,
arr[j] is greater than arr[j + 1], it means they are in the wrong order for ascending sort.temp perform a swap: temp temporarily holds arr[j], arr[j] gets arr[j + 1], and arr[j + 1] gets the value from temp.- Display Sorted Array: After the loops complete, the array
arris fully sorted in ascending order. The program then prints the sorted array.
Other Approaches
While Bubble Sort is great for learning, it's not the most efficient for large datasets. Other algorithms include:
- Selection Sort: Finds the minimum element from the unsorted part and puts it at the beginning.
- Insertion Sort: Builds the final sorted array one item at a time, by inserting each element into its correct position among the already sorted elements.
- Merge Sort: A divide-and-conquer algorithm that divides the array into halves, sorts them recursively, and then merges the sorted halves.
- Quick Sort: Another divide-and-conquer algorithm that picks an element as a pivot and partitions the given array around the picked pivot.
Conclusion
Sorting an array is a foundational skill in programming. Bubble Sort provides a clear, step-by-step method to achieve ascending order, making it an excellent starting point for understanding sorting algorithms. While simpler, its principles of comparison and swapping are core to many other sorting techniques.
Summary
- Array sorting arranges elements in a specific order, such as ascending.
- Bubble Sort repeatedly compares adjacent elements and swaps them if they are in the wrong order.
- It performs
n-1passes, with each pass moving the largest unsorted element to its correct position. - Understanding Bubble Sort lays the groundwork for more complex and efficient sorting algorithms.
- Sorting is vital for data organization, search efficiency, and presentation in various real-world applications.