Bubble Sort
2) Bubble Sort
Aim
To arrange elements in ascending order using Bubble Sort (without functions).
Objective
To study simple comparison-based sorting.
To understand swapping of adjacent elements.
Algorithm
Input number of elements and array.
Repeat for i = 0 to n-1
Repeat for j = 0 to n-i-2
If arr[j] > arr[j+1], swap them.
Print sorted array.
Flowchart
C Code
#include <stdio.h>
int main() {
int n, i, j, temp;
printf("Enter number of elements: ");
scanf("%d", &n);
int arr[n];
printf("Enter array elements: ");
for (i = 0; i < n; i++)
scanf("%d", &arr[i]);
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;
}
}
}
printf("Sorted array: ");
for (i = 0; i < n; i++)
printf("%d ", arr[i]);
return 0;
}
Comments
Post a Comment