- C++

C++: Bubble sort

Abstract

This article aims to record how to code for bubble sort algorithm with C++. Although a sort function has been provided in STL library, it is still useful to understand how to achieve the sort algorithm with basic loops.

Principle

To understand the bubble sort easily, visit the website https://visualgo.net/.

C++ Code

#include <iostream>
#include <vector>

using namespace std;

int main(void)
{
    int temp = 0;
    vector<int> serial;

    //Hint sentence to ask user input numbers.
    cout << "Please input numbers with space to seperate and finished with any non-number character:" << endl;

    //Use a vector as dynamic array to store numbers.
    while(cin >> temp) serial.push_back(temp);

    //To sort n numbers, there are n-1 number required to be swap.
    for(int i = 0; i < serial.size()-1; i++)
    {
        //In the swap of each number, it requred to swap n-i times.
        for(int j = 0; j < serial.size()-1-i; j++)
        {
            //If current number is larger than next number, swap them.
            if(serial[j] > serial[j+1])
            {
                temp = serial[j];
                serial[j] = serial[j+1];
                serial[j+1] = temp;
            }
        }
    }

    //Print the result.
    cout << endl << "From min to max:" << endl;
    for(int i = 0; i < serial.size(); i++)
        cout << serial[i] << " ";
    cout << endl;
    
    return 0;
}

About Ziqi.Yang394

Read All Posts By Ziqi.Yang394

Leave a Reply

Your email address will not be published. Required fields are marked *