How can I rearrange the array to get minimum, average and maximum faster?

I want to rebuild the array again, or std::vectorso that the minimum is the first element, the last element is the maximum, and it arr[(0+lastIdx)/2]will be the middle, the elements before the median is less than the median, the elements after the median will be more. Every time I request min, max and median, I will make changes to the data, and I want to request these three values ​​again again.

Every time I want to reorder an array, the array is another array with the same size.

Using std::nth_element, I can get the median in the right place, and then I could iterate the array to get min and max. For a single array, this achieves O (n) complexity, and obviously this cannot be improved. (Except, perhaps, of constant complexity before O (n))

I need to work with an array, firstly, I rebuild the array and then do something else, this will cause the ordered array to be completely deleted, but new values ​​will not be inserted. then repeat this procedure again and again.

+4
source share
5 answers

- min, max, , . n/2 - 1 permutations .

  • , (O(n) , O(1) )
  • , (O(n) , O(1) )
  • , (O(n) , O(1) )
  • min, max, (0, n-1, n/2)
  • : , 0, , n-1. below , , . above , , . , . , below < above. (O(n) , O(1) )

4, 5: , , , - , .

, pass 1, 2, 3 ,

:

{3, 7, 9, 6, 8, 1, 4, 5, 2}

1, 2, 3: min_pos = 5, max_pos = 2, median_pos = 7, median = 5

swap (0, min_pos)    -> {1, 7, 9, 6, 8, 3, 4, 5, 2}
swap (9, max_pos)    -> {1, 7, 2, 6, 8, 3, 4, 5, 9}
swap (4, median_pos) -> {1, 7, 2, 6, 5, 3, 4, 8, 9}

below_pos = 0 above_pos = 8. . - 7 1. - 4 6.

swap (1, 6) -> {1, 4, 2, 6, 5, 3, 7, 8, 9}

- 6 3. 3 5.

swap (3, 5) -> {1, 4, 2, 3, 5, 6, 7, 8, 9}

{1, 4, 2, 3, 5, 6, 7, 8, 9}

0

- O (log n sqrt (n)), .

. sqrt (n), (n) sqrt (n) . , , " n1 <= x1" ( n1 sqrt (n), x1 - n1), " n2 <= x2" ( n2 n/2 - sqrt (n)/n, x2 - n2), " n3 <= x3" ( n3 - n/2 + sqrt (n)/n, x3 - n3 - ) " n4 <= x4", n4 n - sqrt (n), n4 - x4. 0 n1, n2 n3 n4 n-1.

, , sqrt (n).

, n1, n2, n3 n4 , , 0 n1, n2 n3, n4 - n-1. n1, n2, n3, n4 , , . , .

BTW. , .

0

, , , min/max:

:

  • O(1);
  • ​​ O(log N);

:

  • N ( N/2 ) N - 2N N O(N).

++ STL, : std::make_heap, std::push_heap std::pop_heap.

, , .

, - . N , .

-1

O (n) , , , , , .

, - , , . , , , , , ?

Pro: .

Con: .

-3

Certainly, you cannot do it faster than in O (N), because you need to look through all the elements, even to find the minimum.

You can, of course, talk about code optimization within the complexity of O (N) (that is, optimizing a constant to N).

Or will you do the same operation several times on a slightly modified array?

-3
source

Source: https://habr.com/ru/post/1584513/