given an array, for each element, find out the total number of elements lesser than it, which appear to the right of it

后端 未结 10 1798
傲寒
傲寒 2021-02-04 11:43

I had previously posted a question, Given an array, find out the next smaller element for each element now, i was trying to know , if there is any way to find out \"given an ar

10条回答
  •  情书的邮戳
    2021-02-04 12:00

    I think is it possible to do it in O(nlog(n))with a modified version of quicksort. Basically each time you add an element to less, you check if this element rank in the original array was superior to the rank of the current pivot. It may look like

    oldrank -> original positions 
    count -> what you want
    function quicksort('array')
      if length('array') ≤ 1
          return 'array'  // an array of zero or one elements is already sorted
      select and remove a pivot value 'pivot' from 'array'
      create empty lists 'less' and 'greater'
      for each 'x' in 'array'
          if 'x' ≤ 'pivot' 
             append 'x' to 'less'
             if oldrank(x) > = oldrank(pivot)  increment count(pivot)
          else 
             append 'x' to 'greater'
             if oldrank(x) <  oldrank(pivot)  increment count(x) //This was missing
      return concatenate(quicksort('less'), 'pivot', quicksort('greater')) // two recursive calls
    

    EDIT:

    Actually it can be done using any comparison based sorting algorithm . Every time you compare two elements such that the relative ordering between the two will change, you increment the counter of the bigger element.

    Original pseudo-code in wikipedia.

提交回复
热议问题