Bubble Sort

Textbook


Description:

Example:

Note

Idea:

  • Stable
  • In place
  • Time: O(n2)

Code:

#include <iostream>
#include <vector>
#include <climits>

using namespace std;

void bubbleSort(vector<int> & nums){
    int n=nums.size();

    for(int i=n-1; i>0; --i){
        for(int j=0; j<i; ++j ){
            if(nums[j]>nums[j+1]){
                swap(nums[j], nums[j+1]);
            }
        }
    }
}

int main(){
    vector<int> input={3,4,2,5,6,7,2,3,3,8,9,23,43,22,1,23};

    for(auto e: input){
        cout<<e<<' ';
    } cout<<'\n';

    bubbleSort(input);

    for(auto e: input){
        cout<<e<<' ';
    } cout<<'\n';

}

results matching ""

    No results matching ""