1. Introduction
Sorting is a fundamental operation in computer science, and it has vast applications in real-world scenarios, from arranging records in databases to enhancing search operations. In this tutorial, we'll guide you through a simple C program that sorts an array in ascending order using the Bubble Sort algorithm.
2. Program Overview
The program will:
1. Take the number of elements and the array of elements as input from the user.
2. Use the Bubble Sort algorithm to sort the array elements in ascending order.
3. Display the sorted array.
3. Code Program
#include <stdio.h> // Include standard I/O library for input-output operations.
int main() { // Begin main function.
int n, i, j, temp; // Declare variables to store the array size, loop counters, and a temporary variable for swapping.
printf("Enter number of elements: "); // Prompt user for input.
scanf("%d", &n); // Store the number of elements in 'n'.
int arr[n]; // Declare an array of size 'n'.
printf("Enter %d integers: ", n); // Prompt user for array elements.
for(i = 0; i < n; i++) {
scanf("%d", &arr[i]); // Read each array element.
}
// Implementing Bubble Sort
for(i = 0; i < n - 1; i++) {
for(j = 0; j < n - 1 - i; j++) {
if(arr[j] > arr[j + 1]) { // Compare adjacent elements.
// Swap arr[j] and arr[j+1] if arr[j] is greater.
temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
printf("Sorted array in ascending order:\n");
for(i = 0; i < n; i++) {
printf("%d ", arr[i]); // Print each element of the sorted array.
}
return 0; // End the program.
}
Output:
Enter number of elements: 5 Enter 5 integers: 64 34 25 12 22 Sorted array in ascending order: 12 22 25 34 64
4. Step By Step Explanation
1. Header Inclusion: The standard input-output library #include <stdio.h> is used for input-output operations.
2. Main Function: Execution of every C program begins from the main() function.
3. Variable Declaration:
- n holds the number of elements in the array.
- i and j are used as loop counters.
- temp is a temporary variable for swapping array elements.
4. Reading Input:
- We first prompt and read the number of elements.
- Next, we prompt the user for each array element and store it in arr.
5. Bubble Sort:
- The essence of Bubble Sort is to repeatedly step through the list, compare adjacent elements, and swap them if they are in the wrong order. The pass through the list is repeated until the list is sorted.
- Our outer loop runs n-1 times, representing each pass.
- The inner loop compares adjacent elements and swaps them if they`re out of order.
6. Printing Result: Finally, we print the sorted array.
This Bubble Sort method is simple but not the most efficient sorting algorithm. However, it's easy to understand and implement, making it suitable for beginners.
Comments
Post a Comment
Leave Comment