- How to sort an array in ascending order
- How bubble sort algorithm works
- How to swap elements using a temporary variable
- Step-by-step explanation of the program
- Practice exercises to test your understanding
Introduction
In this tutorial, we will learn how to write a C program to sort an array in ascending order.
Sorting an array is one of the most important operations in programming. It is used in many real-world applications, such as:
- Organizing data for easy searching and retrieval
- Sorting student grades, employee salaries, or customer lists
- Preparing data for other algorithms (like binary search)
- Creating ranked or ordered lists
š” Key Point: In ascending order, elements are arranged from smallest to largest. This program uses the bubble sort algorithm, which repeatedly steps through the list, compares adjacent elements, and swaps them if they are in the wrong order.
C Program to Sort Array in Ascending Order (Using Bubble Sort)
#include <stdio.h>
int main() {
int n, i, j, temp;
// Ask user for number of elements
printf("Enter the number of elements: ");
scanf("%d", &n);
// Declare array
int arr[n];
// Read elements into the array
printf("Enter %d elements:\n", n);
for(i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}
// Bubble sort - sort in ascending order
for(i = 0; i < n-1; i++) {
for(j = 0; j < n-i-1; j++) {
if(arr[j] > arr[j+1]) {
// Swap arr[j] and arr[j+1]
temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
}
// Display sorted array
printf("\nArray in ascending order: ");
for(i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
printf("\n");
return 0;
}
Sample Output
Enter the number of elements: 6 Enter 6 elements: 50 20 40 10 30 60 Array in ascending order: 10 20 30 40 50 60
Another Example:
Enter the number of elements: 5 Enter 5 elements: 25 10 35 15 20 Array in ascending order: 10 15 20 25 35
Example with Negative Numbers:
Enter the number of elements: 7 Enter 7 elements: -5 10 -2 8 0 -10 3 Array in ascending order: -10 -5 -2 0 3 8 10
Program Explanation
Let's break down the code step by step:
- Include Header File:
#include <stdio.h>includes the standard input/output library. - Declare Variables:
int n;ā stores the number of elementsint i, j;ā loop countersint temp;ā temporary variable for swapping
- Get User Input: Prompts the user to enter the number of elements and then reads them into the array.
- Bubble Sort Algorithm:
- Outer Loop:
for(i = 0; i < n-1; i++)ā runs n-1 times - Inner Loop:
for(j = 0; j < n-i-1; j++)ā compares adjacent elements - Comparison: If
arr[j] > arr[j+1], swap them - After each pass, the largest element "bubbles up" to the end
- Outer Loop:
- Display Result: Prints the sorted array.
- Return:
return 0;indicates successful program execution.
š Note: Bubble sort has a time complexity of O(n²). It is not efficient for large arrays, but it's easy to understand and implement. For larger arrays, consider using Quick Sort or Merge Sort.
Bubble Sort Algorithm
Step-by-step explanation of bubble sort:
- Start with the first element
- Compare the current element with the next element
- If the current element is greater than the next element, swap them
- Move to the next element and repeat step 2-3
- After one complete pass, the largest element is at the end
- Repeat the process for the remaining elements (excluding the last)
- Stop when all elements are sorted
Visual Example
Let's see how bubble sort works on the array [50, 20, 40, 10, 30]:
Pass 1:
[50, 20, 40, 10, 30] ā Swap 50 and 20 ā [20, 50, 40, 10, 30]
[20, 50, 40, 10, 30] ā Swap 50 and 40 ā [20, 40, 50, 10, 30]
[20, 40, 50, 10, 30] ā Swap 50 and 10 ā [20, 40, 10, 50, 30]
[20, 40, 10, 50, 30] ā Swap 50 and 30 ā [20, 40, 10, 30, 50]
Result: [20, 40, 10, 30, 50] ā 50 is now in correct position
Pass 2:
[20, 40, 10, 30, 50] ā Swap 40 and 10 ā [20, 10, 40, 30, 50]
[20, 10, 40, 30, 50] ā Swap 40 and 30 ā [20, 10, 30, 40, 50]
Result: [20, 10, 30, 40, 50] ā 40 is now in correct position
Pass 3:
[20, 10, 30, 40, 50] ā Swap 20 and 10 ā [10, 20, 30, 40, 50]
Result: [10, 20, 30, 40, 50] ā 30 is now in correct position
Pass 4:
[10, 20, 30, 40, 50] ā No swaps needed, array is sorted!
Optimized Bubble Sort
We can optimize bubble sort by adding a flag to check if any swaps were made in a pass. If no swaps were made, the array is already sorted and we can break early.
#include <stdio.h>
int main() {
int n, i, j, temp;
int swapped;
printf("Enter the number of elements: ");
scanf("%d", &n);
int arr[n];
printf("Enter %d elements:\n", n);
for(i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}
// Optimized bubble sort
for(i = 0; i < n-1; i++) {
swapped = 0;
for(j = 0; j < n-i-1; j++) {
if(arr[j] > arr[j+1]) {
temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
swapped = 1;
}
}
// If no swaps were made, array is already sorted
if(swapped == 0) {
break;
}
}
printf("\nArray in ascending order: ");
for(i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
printf("\n");
return 0;
}
š» Practice Exercise
Challenge 1: Modify the program to sort the array in descending order.
Challenge 2: Write a program to sort an array using selection sort instead of bubble sort.
š Click to Show Solution for Challenge 1
#include <stdio.h>
int main() {
int n, i, j, temp;
printf("Enter the number of elements: ");
scanf("%d", &n);
int arr[n];
printf("Enter %d elements:\n", n);
for(i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}
// Sort in descending order (change > to <)
for(i = 0; i < n-1; i++) {
for(j = 0; j < n-i-1; j++) {
if(arr[j] < arr[j+1]) { // Compare for descending
temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
}
printf("\nArray in descending order: ");
for(i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
printf("\n");
return 0;
}
Frequently Asked Questions
1. How do you sort an array in ascending order in C?
You can use sorting algorithms like bubble sort, selection sort, or insertion sort. The program above uses bubble sort, which compares adjacent elements and swaps them if they are out of order.
2. What is the time complexity of bubble sort?
The time complexity of bubble sort is O(n²) in the worst and average cases, and O(n) in the best case (when the array is already sorted).
3. Can I sort an array using the qsort function?
Yes, C provides the qsort() function in stdlib.h library. It's more efficient (O(n log n)) and is recommended for large arrays.
4. What is the difference between ascending and descending order?
Ascending order means arranging elements from smallest to largest (e.g., 1, 2, 3, 4, 5). Descending order means arranging from largest to smallest (e.g., 5, 4, 3, 2, 1).
5. Which sorting algorithm is best for beginners?
Bubble sort is the easiest to understand and implement. It's a great starting point for learning sorting algorithms. Once you understand bubble sort, you can move on to more efficient algorithms like Quick Sort or Merge Sort.
š” Tip: When sorting large arrays, use more efficient algorithms like qsort() or Quick Sort. Bubble sort is best for learning and small arrays.