optimized bubble sort


#include <iostream>

#include <vector>


using namespace std;


int main()

{

    vector<int> vec = {10,20,30};

    

    //booble sort

    bool  check = false;

    

    for(int i = 0; i<= vec.size(); i++)

    {

         

        for (int j= i+1; j<vec.size(); j++)

        {

            

            if(vec[j] < vec[i])

            {

                int temp = vec[i];

                vec[i] = vec[j];

                vec[j] = temp;

                check = true;

            }

            

        }

        

        if(!check)

        {

            cout << "vector is alreday sorted" <<endl;

            break;

        }

    }

    

    for(int x : vec)

    {

        cout << x << endl;

    }


    return 0;

}

0(n) - complexity  for sorted data 

Comments

Popular posts from this blog

Implementation of Queue using Array

Printing the odd and even no using Pthread

Print even and odd using two thread in synchronized way