Loading your workspace…
Loading your workspace…
Sort a list of N integers into ascending order using bubble sort, swapping adjacent elements that are out of order.
#include <stdio.h>
#define MAX 100
void bubble_sort(int arr[], int n) {
int pass, i, temp, swapped;
for (pass = 0; pass < n - 1; pass++) {
swapped = 0;
for (i = 0; i < n - 1 - pass; i++) {
if (arr[i] > arr[i + 1]) {
temp = arr[i];
arr[i] = arr[i + 1];
arr[i + 1] = temp;
swapped = 1;
}
}
if (!swapped) {
break;
}
}
}
int main(void) {
int arr[MAX];
int n, i;
printf("Enter the number of elements (1-%d):\n", MAX);
if (scanf("%d", &n) != 1 || n < 1 || n > MAX) {
printf("Error: invalid size\n");
return 1;
}
printf("Enter %d numbers:\n", n);
for (i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}
bubble_sort(arr, n);
printf("Sorted in ascending order:\n");
for (i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
printf("\n");
return 0;
}
Input
6
5 -2 9 5 0 3Output
Enter the number of elements (1-100):
Enter 6 numbers:
Sorted in ascending order:
-2 0 3 5 5 9 Input
1
7Output
Enter the number of elements (1-100):
Enter 1 numbers:
Sorted in ascending order:
7 After the first pass the largest value has bubbled to the end, so each later pass can stop one position earlier. The swapped flag lets the function finish early when the array is already in order.
Bubble sort does about n² comparisons in the worst case, so it is a teaching algorithm rather than a fast one; the loop structure is the point of the exercise.
Edit the program and press Run. It is free and needs no sign-in.
Copy a sample and paste it into the STDIN box in the editor before you press Run.
6 5 -2 9 5 0 3
Expected output
Enter the number of elements (1-100): Enter 6 numbers: Sorted in ascending order: -2 0 3 5 5 9
1 7
Expected output
Enter the number of elements (1-100): Enter 1 numbers: Sorted in ascending order: 7
O(n²), because up to n - 1 passes each compare up to n - 1 pairs.
It detects a pass with no swaps, meaning the array is sorted, and ends the sort early. The best case on sorted input becomes O(n).
Yes. Equal elements are never swapped, so their original order is preserved.
Each pass places the largest remaining value at the end, so those positions are already in their final place.
Arrays are passed as pointers, so the swaps change the caller's array directly.
Back to all VTU BPOPS103 lab programs.