Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
C program to sort an array in an ascending order
In C programming, sorting an array in ascending order means arranging elements from smallest to largest value. This is a fundamental operation that can be implemented using various algorithms, with bubble sort being one of the most commonly taught approaches.
Syntax
// Basic bubble sort algorithm
for (i = 0; i < n; i++) {
for (j = i + 1; j < n; j++) {
if (arr[i] > arr[j]) {
// Swap elements
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
Array Declaration
Before sorting, we need to understand how to declare arrays in C ?
datatype array_name[size];
For example:
int numbers[10]; // Array of 10 integers float marks[50]; // Array of 50 floating-point numbers
Example: Sorting Array in Ascending Order
The following program demonstrates how to sort an array using the bubble sort algorithm ?
#include <stdio.h>
int main() {
int num[20];
int i, j, temp, n;
printf("Enter number of elements in an array: ");
scanf("%d", &n);
printf("Enter the elements:<br>");
for (i = 0; i < n; i++) {
scanf("%d", &num[i]);
}
// Bubble sort algorithm
for (i = 0; i < n; i++) {
for (j = i + 1; j < n; j++) {
if (num[i] > num[j]) {
// Swap elements
temp = num[i];
num[i] = num[j];
num[j] = temp;
}
}
}
printf("The numbers in ascending order:<br>");
for (i = 0; i < n; i++) {
printf("%d ", num[i]);
}
printf("<br>");
return 0;
}
Enter number of elements in an array: 5 Enter the elements: 64 34 25 12 22 The numbers in ascending order: 12 22 25 34 64
How It Works
The bubble sort algorithm works by:
- Nested loops: The outer loop runs for each element, inner loop compares adjacent elements
-
Comparison: If
num[i] > num[j], elements are swapped - Swapping: Uses a temporary variable to exchange positions
- Time Complexity: O(n²) for worst case, O(n) for best case
Key Points
- Bubble sort is simple but not efficient for large datasets
- The algorithm makes multiple passes through the array
- After each pass, the largest element "bubbles up" to its correct position
- Space complexity is O(1) as it sorts in-place
Conclusion
Sorting arrays in ascending order using bubble sort is an excellent way to understand basic sorting concepts in C. While not the most efficient algorithm, it provides a clear foundation for learning more advanced sorting techniques like quick sort and merge sort.
