C++ Online Compiler
Example: Gnome Sort Implementation in C++
C
C++
C#
Java
Python
PHP
main.cpp
STDIN
Run
// Gnome Sort Implementation #include <iostream> #include <vector> // Using std::vector for dynamic array #include <algorithm> // For std::swap // Function to perform Gnome Sort on a vector void gnomeSort(std::vector<int>& arr) { int index = 0; // Current position int n = arr.size(); // Size of the vector while (index < n) { if (index == 0) { // If at the beginning, just move forward index++; } else if (arr[index] >= arr[index - 1]) { // If current element is in order with the previous one, move forward index++; } else { // If current element is out of order, swap with previous std::swap(arr[index], arr[index - 1]); // Move back to recheck the new previous element index--; } } } // Function to print the elements of a vector void printVector(const std::vector<int>& arr) { for (int x : arr) { std::cout << x << " "; } std::cout << std::endl; } int main() { // Step 1: Initialize an unsorted vector std::vector<int> data = {34, 2, 10, -9, 50, 1, 7}; // Step 2: Print the original vector std::cout << "Original vector: "; printVector(data); // Step 3: Apply Gnome Sort gnomeSort(data); // Step 4: Print the sorted vector std::cout << "Sorted vector (Gnome Sort): "; printVector(data); return 0; }
Output
Clear
ADVERTISEMENTS