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