We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
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.
voidcountSwaps(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.intnumSwaps=0;map<int,int>numTracker;for(intnum:a){for(pair<int,int>trackedNum:numTracker){// Compare a number to all numbers before to see how many of them it is smaller thanif(num<trackedNum.first){// Duplicate numbers must also be considerednumSwaps+=trackedNum.second;}}// Add the number at this index to our mapnumTracker[num]++;}// Smallest and largest numbers can be found in O(n) time.intminNum=*std::min_element(a.begin(),a.end());intmaxNum=*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.
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Sorting: Bubble Sort
You are viewing a single comment's thread. Return to all 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.
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.