Program 8
Develop a program to
sort the given set of N numbers using
Bubble Sort algorithm. Bubble sort is a simple sorting algorithm
that repeatedly steps through the list, compares adjacent elements, and swaps them if they are in
the wrong order. The pass through the list is repeated until the list is sorted.
Algorithm
- Input: Read the number of elements (n) from user
- Array Input: Read n numbers into an array from user
- Outer Loop: Run loop from i = 0 to n-2 (n-1 passes)
- Inner Loop: For each pass, run loop from j = 0 to n-i-2
- Compare: Compare arr[j] with arr[j+1]
- Swap: If arr[j] > arr[j+1], swap the elements using temporary variable
- Repeat: Continue until all passes are completed
- Output: Display the sorted array
Flowchart
START
→
Input n
→
Input Array
→
i = 0 to n-2
→
j = 0 to n-i-2
→
arr[j] > arr[j+1]?
→
Swap
→
Display Sorted Array
→
STOP
Code
#include <stdio.h>
int main() {
int n, i, j, temp;
printf("Enter number of elements: ");
scanf("%d", &n);
int arr[n];
printf("Enter %d numbers:\n", n);
for (i = 0; i < n; i++)
scanf("%d", &arr[i]);
// Bubble Sort
for (i = 0; i < n - 1; i++) {
for (j = 0; j < n - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
// Swap
temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
// Print sorted array
printf("Sorted numbers:\n");
for (i = 0; i < n; i++)
printf("%d ", arr[i]);
printf("\n");
return 0;
}