Sorting: Bubble Sort

  • + 0 comments

    Bubble sort swaps every time a larger number is to the left of a smaller number. Therefore, if we count the number of times a larger number is left of a smaller one, we have the number of swaps.

    void countSwaps(vector<int> a) {
        // The number of swaps = for each number, how many smaller numbers are right of it
        // Put all numbers in a map and check against each element to the right of it
        // Still n^2 time, but removes necessity of all swaps, improving speed
        // If n=a.length(), number of checks is (n)(n-1)/2, the triangle number of n-1.
        int numSwaps = 0;
        map<int, int> numTracker;
        for (int num : a) {
            for (pair<int, int> trackedNum : numTracker) {
                // Compare a number to all numbers before to see how many of them it is smaller than
                if (num < trackedNum.first) {
                    // Duplicate numbers must also be considered
                    numSwaps += trackedNum.second;
                }
            }
            // Add the number at this index to our map
            numTracker[num]++;
        }
        
        // Smallest and largest numbers can be found in O(n) time.
        int minNum = * std::min_element(a.begin(), a.end());
        int maxNum = * std::max_element(a.begin(), a.end());
        
        cout << "Array is sorted in " << numSwaps << " swaps." << endl;
        cout << "First Element: " << minNum << endl;
        cout << "Last Element: " << maxNum << endl;
    }
    

    This does not improve time complexity, but allows us to avoid swapping entirely. In practice, it should be more efficient, for the same reason insertion and selection sort are "better" than bubble sort despite the same time complexity.