Friday 21 October 2016

Bubble Sort (CTCI)

Problem: Bubble Sort

int bubbleSort(vector<int> *a, int n)
{
    //cout<<a->at(1)<<endl;
    int totalSwap = 0;
    for (int i = 0; i < n; i++)
    {
        // Track number of elements swapped during a single array traversal
        int numberOfSwaps = 0;

        for (int j = 0; j < n - 1; j++)
        {
            // Swap adjacent elements if they are in decreasing order
            if (a->at(j) > a->at(j+1))
            {
                swap(a->at(j), a->at(j+1));
                numberOfSwaps++;
            }
        }
        totalSwap += numberOfSwaps;
        // If no elements were swapped during a traversal, array is sorted
        if (numberOfSwaps == 0)
        {
            break;
        }
    }
    return totalSwap;
}

int main(){
    int n;
    cin >> n;
    vector<int> a(n);
    for(int a_i = 0;a_i < n;a_i++){
       cin >> a[a_i];
    }
    cout<<"Array is sorted in "<<bubbleSort(&a, n)<<" swaps."<<endl;
    cout<<"First Element: "<<a[0]<<endl;
    cout<<"Last Element: "<<a[n-1]<<endl;
    return 0;
}

No comments:

Post a Comment