POP Lab Manual

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.
Bubble Sort Concept:
Time Complexity: O(n²) - Worst & Average Case
Time Complexity: O(n) - Best Case (Already Sorted)
Space Complexity: O(1) - In-place sorting

Algorithm

  1. Input: Read the number of elements (n) from user
  2. Array Input: Read n numbers into an array from user
  3. Outer Loop: Run loop from i = 0 to n-2 (n-1 passes)
  4. Inner Loop: For each pass, run loop from j = 0 to n-i-2
  5. Compare: Compare arr[j] with arr[j+1]
  6. Swap: If arr[j] > arr[j+1], swap the elements using temporary variable
  7. Repeat: Continue until all passes are completed
  8. 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;
}

Output


// Output 1 - Small dataset
Enter number of elements: 5
Enter 5 numbers:
64 34 25 12 22
Sorted numbers:
12 22 25 34 64 

// Output 2 - Already sorted array
Enter number of elements: 6
Enter 6 numbers:
10 20 30 40 50 60
Sorted numbers:
10 20 30 40 50 60 

// Output 3 - Reverse sorted array (worst case)
Enter number of elements: 7
Enter 7 numbers:
70 60 50 40 30 20 10
Sorted numbers:
10 20 30 40 50 60 70 

// Output 4 - Array with duplicate elements
Enter number of elements: 8
Enter 8 numbers:
15 32 15 47 23 32 8 47
Sorted numbers:
8 15 15 23 32 32 47 47 

// Output 5 - Single element
Enter number of elements: 1
Enter 1 numbers:
42
Sorted numbers:
42 

// Output 6 - Negative numbers
Enter number of elements: 6
Enter 6 numbers:
-5 3 -12 8 -1 0
Sorted numbers:
-12 -5 -1 0 3 8