C Online Compiler
Example: Bubble Sort using Function in C
C
C++
C#
Java
Python
PHP
main.c
STDIN
Run
// Bubble Sort using Function #include <stdio.h> // Function to perform Bubble Sort void bubbleSort(int arr[], int n) { // Step 1: Outer loop for passes (n-1 passes) for (int i = 0; i < n - 1; i++) { // Step 2: Inner loop for comparisons and swaps in each pass for (int j = 0; j < n - i - 1; j++) { // Step 3: Compare adjacent elements if (arr[j] > arr[j + 1]) { // Step 4: Swap elements if they are in the wrong order int temp = arr[j]; arr[j] = arr[j + 1]; arr[j + 1] = temp; } } } } // Function to print an array void printArray(int arr[], int size) { // Step 1: Iterate through the array for (int i = 0; i < size; i++) { // Step 2: Print each element printf("%d ", arr[i]); } printf("\n"); } int main() { // Step 1: Define an unsorted array int arr[] = {64, 34, 25, 12, 22, 11, 90}; // Step 2: Calculate the size of the array int n = sizeof(arr) / sizeof(arr[0]); // Step 3: Print the original array printf("Original array: "); printArray(arr, n); // Step 4: Call the bubbleSort function to sort the array bubbleSort(arr, n); // Step 5: Print the sorted array printf("Sorted array: "); printArray(arr, n); return 0; }
Output
Clear
ADVERTISEMENTS