Cracking the Coding Interview: Sorting – Bubble Sort

Here’s my solution to the challenge: https://www.hackerrank.com/challenges/ctci-bubble-sort

int bubbleSort(vector& data) {
    int numberOfSwaps = 0;
    
    for(int i = 0; i < data.size(); i++) {
        for(int j = 0; j  data[j+1]) {
                swap(data[j], data[j+1]);
                numberOfSwaps++;
            }
        }
        if(numberOfSwaps == 0) {
            break;
        }
    }
    return numberOfSwaps;
}

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

All my solutions to HackerRank challenges can be found here: https://github.com/sdulaney/hackerrank

Leave a Comment