#include <stdio.h>
// Function to perform bubble sort
void bubbleSort(int arr[], int n) {
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
// Swap arr[j] and arr[j + 1]
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}
int main() {
int N;
// Accept the number of elements
printf("Enter the number of elements: ");
scanf("%d", &N);
int arr[N];
// Accept the elements
printf("Enter %d numbers:\n", N);
for (int i = 0; i < N; i++) {
scanf("%d", &arr[i]);
}
// Sort the array
bubbleSort(arr, N);
// Display the sorted array
printf("Sorted numbers in ascending order:\n");
for (int i = 0; i < N; i++) {
printf("%d ", arr[i]);
}
printf("\n");
return 0;
}
Explanation
Include Header Files:
#include <stdio.h>
- This line includes the standard input-output library, which is necessary for using
printf
andscanf
.
- This line includes the standard input-output library, which is necessary for using
Bubble Sort Function:
void bubbleSort(int arr[], int n) {
- This function sorts the array
arr
of sizen
using the bubble sort algorithm. - The outer loop runs
n-1
times, and the inner loop compares adjacent elements, swapping them if they are in the wrong order.
- This function sorts the array
Swapping Elements:
if (arr[j] > arr[j + 1]) { int temp = arr[j]; arr[j] = arr[j + 1]; arr[j + 1] = temp; }
- If the current element is greater than the next one, they are swapped to move the larger element towards the end of the array.
Main Function:
int main() {
- The main function starts the execution of the program.
Input Number of Elements:
printf("Enter the number of elements: "); scanf("%d", &N);
- The user is prompted to enter the number of integers they want to sort, which is stored in
N
.
- The user is prompted to enter the number of integers they want to sort, which is stored in
Dynamic Array Declaration:
int arr[N];
- An array
arr
of sizeN
is declared to store the numbers.
- An array
Input Elements:
for (int i = 0; i < N; i++) { scanf("%d", &arr[i]); }
- A loop is used to read
N
integers from the user into the array.
- A loop is used to read
Sorting the Array:
bubbleSort(arr, N);
- The
bubbleSort
function is called to sort the array in ascending order.
- The
Display Sorted Array:
printf("Sorted numbers in ascending order:\n"); for (int i = 0; i < N; i++) { printf("%d ", arr[i]); }
- The sorted array is printed to the console.
Return Statement:
return 0;
- Indicates that the program executed successfully.