bubble sort c program code example

Example 1: bubble sort c++ template

// template <class t>
// void bubble <t>::sort(int n)
template < typename T > void bubble_sort( T a[], int n )
{
    int i,j;
    //t temp;
    T temp ;
    for(i=0; i<n; i++)
    {
        for(j=i+1; j<n; j++)
        {
            if(a[i]>a[j]) //bubble sort algo
            {
                temp=a[i];
                a[i]=a[j];
                a[j]=temp;
            }
        }
    }
}

Example 2: bubble sort integers

for (int i = 0; i < n-1; i++) 
            for (int j = 0; j < n-i-1; j++) 
                if (arr[j] > arr[j+1]) 
                { 
                    // swap arr[j+1] and arr[i] 
                    int temp = arr[j]; 
                    arr[j] = arr[j+1]; 
                    arr[j+1] = temp; 
                }

Example 3: bubble sort program in c++

cout<<"\n Hello World ";

Tags: