Sort the array into ascending order.
Learn how to implement Bubble Sort algorithm in C
๐งพ Step-by-Step Explanation
๐น Step 1: Include Header File
#include <stdio.h>
This standard library provides:
printf()for output displayscanf()for user input- Essential I/O functions for console operations
๐น Step 2: Declare Variables and Array
int arr[100], n, i, j, temp;
- arr[100]: Array with capacity for 100 integers
- n: Actual number of elements to sort
- i, j: Loop counters for sorting passes
- temp: Temporary variable for swapping elements
๐น Step 3: Input Size and Elements
printf("Enter the number of elements: ");
scanf("%d", &n);
for(i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}
- First gets the array size (n ≤ 100)
- Then collects each element from user
- Stores elements in sequential array positions
- Uses formatted input with index display
๐น Step 4: Sort the Array (Bubble Sort)
for(i = 0; i < n - 1; i++) {
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;
}
}
}
Bubble Sort implementation:
- Outer loop: Controls number of passes (n-1 passes needed)
- Inner loop: Compares adjacent elements in each pass
- Comparison: Checks if elements are in wrong order
- Swapping: Uses temp variable to exchange elements
- With each pass, largest unsorted element "bubbles up" to correct position
๐น Step 5: Display Sorted Array
for(i = 0; i < n; i++) {
printf("arr[%d] = %d\n", i, arr[i]);
}
- Prints all elements in sorted order
- Shows both index and value for each element
- Verifies the successful sorting
- Uses newline character for clean output
๐งช Sample Output
Enter the number of elements: 5
Enter 5 elements:
arr[0]: 30
arr[1]: 10
arr[2]: 50
arr[3]: 20
arr[4]: 40
Array in ascending order:
arr[0] = 10
arr[1] = 20
arr[2] = 30
arr[3] = 40
arr[4] = 50