C++ Online Compiler
Example: Bubble Sort without function in C++
C
C++
C#
Java
Python
PHP
main.cpp
STDIN
Run
// Bubble Sort without function #include <iostream> // Required for input/output operations int main() { // Step 1: Declare and initialize an unsorted array int arr[] = {64, 34, 25, 12, 22, 11, 90}; int n = sizeof(arr) / sizeof(arr[0]); // Calculate the number of elements // Step 2: Print the original array std::cout << "Original array: "; for (int i = 0; i < n; i++) { std::cout << arr[i] << " "; } std::cout << std::endl; // Step 3: Implement Bubble Sort using nested loops // Outer loop for passes (n-1 passes are sufficient) 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 (arr[j] > arr[j + 1]) { // If the current element is greater than the next, swap them int temp = arr[j]; arr[j] = arr[j + 1]; arr[j + 1] = temp; } } } // Step 4: Print the sorted array std::cout << "Sorted array (ascending): "; for (int i = 0; i < n; i++) { std::cout << arr[i] << " "; } std::cout << std::endl; return 0; // Indicate successful execution }
Output
Clear
ADVERTISEMENTS