C Online Compiler
Example: Bubble Sort in Ascending Order in C
C
C++
C#
Java
Python
PHP
main.c
STDIN
Run
// Bubble Sort in Ascending Order #include <stdio.h> void bubbleSort(int arr[], int n) { // Outer loop for passes through the array for (int i = 0; i < n - 1; i++) { // Inner loop for comparisons and swaps in each pass for (int j = 0; j < n - i - 1; j++) { // Compare adjacent elements // If the element on the left is greater than the element on the right, swap them if (arr[j] > arr[j + 1]) { // Perform swap using a temporary variable int temp = arr[j]; arr[j] = arr[j + 1]; arr[j + 1] = temp; } } } } // Function to print the array void printArray(int arr[], int size) { for (int i = 0; i < size; i++) { printf("%d ", arr[i]); } printf("\n"); } int main() { // Step 1: Initialize an unsorted array int arr[] = {64, 34, 25, 12, 22, 11, 90}; int n = sizeof(arr) / sizeof(arr[0]); // Calculate the size of the array printf("Original array: \n"); printArray(arr, n); // Step 2: Call the bubbleSort function to sort the array bubbleSort(arr, n); printf("Sorted array in ascending order: \n"); printArray(arr, n); return 0; }
Output
Clear
ADVERTISEMENTS