Number of swaps performed by Bubble-Sort on a given array

こ雲淡風輕ζ 提交于 2019-12-11 13:43:44

问题


I have been given an array and I'm asked to find out the number of Swaps required to sort the array using Bubble Sort

Now we know that, we can find the comparisons by n(n-1)/2 but what I need is the number of actual swaps

My first instinct was to use bubble sort and with each swap(), I incremented a Swap variable. But the time complexity of this is a very slow process and I'd like your help to find an optimized way to solve my dilemma

P.S.: I also need to compare whether it is faster to sort it in ascending or descending.... Sorting it twice doubles the time.

Edit:

Sorry if I wan't clear enough. I want to find the swaps without using Bubble Sort at all.


回答1:


Regard the applied swap() to a[i] and a[i+1] as a bubble-up of a[i]. Now, asking how many swaps are going to happen is the same as asking how many bubble-up operations are going to happen. Well, and how many do we have of those?

Each a[i] will bubble-up for each position j > i, where a[j]<a[i]. In words a[i] will bubble-up for each position to the right, where the elements value at that position is smaller than a[i] itself. A pair of elements satisfying this condition is what is known as an inversion of a[].

So reformulating your question we could ask: What is the total number of inversions in a[]? (a.k.a. What is the inversion number of a[]?)

This is a well known problem and besides some obvious approaches running in O(n^2) a typical approach to this problem is to tweak merge-sort a bit in order to find this number. And since merge-sort runs in O(n*log(n)) you get the same running time to find the inversion number of a[].

Now that you know that you can tweak merge-sort, I suggest you give it a try on your own on how to do it exactly.

Hint: The main question you have to answer is: When positioning a single element during a merge-step of two arrays, how many inversion did I fix? Then simply add up all of those.

In case you still are stuck after giving it some thought, you can have a look at some full blown solutions here:

  • http://www.geeksforgeeks.org/counting-inversions/
  • Counting inversions in an array


来源:https://stackoverflow.com/questions/31903666/number-of-swaps-performed-by-bubble-sort-on-a-given-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!