-2

I have an array of elements A1,A2,...,An.

The probability of a user searching for each element are P1,P2,...,Pn.

If the elements are rearranged, will the average case of the algorithm change?

Edit : I have posted the question, which appeared in my exam.

Question 3A

Bhargav Rao
  • 50,140
  • 28
  • 121
  • 140
Sudarshan Sunder
  • 190
  • 3
  • 13

2 Answers2

2

The expected number of comparisons is sum_{i=1...n}(i * p_i).

Re-ordering the elements in descending order reduces the expectation. That's intuitive since by looking at the most probable choices first will reduce, on average, the number of elements looked at before you find a particular choice.

As an example, suppose there's three items k1, k2, k3 with match probabilities 10%, 30% and 60%.

Then in the order k1, k2, k3, the expected number of comparisons is 1*0.1 + 2*0.3 + 3*0.6 = 2.5

With the most likely first: k3, k2, k1, the expected number of comparisons is 1*0.6 + 2*0.3 + 3*0.1 = 1.5

Paul Hankin
  • 54,811
  • 11
  • 92
  • 118
-1

No, because it takes O(1) time to access an element in array and it does not depend on a position of this element in array. So arr[0] and arr[10000] should take the same amount of time.

If you will have something like a linked list or a binary tree, then it makes sense to put elements that are accessed with higher probability closer to the beginning.

Salvador Dali
  • 214,103
  • 147
  • 703
  • 753
  • @polasairam I think it answers exactly what OP wanted. Can you explain why it has nothing to do (who knows may be I misinterpretted it) – Salvador Dali Mar 01 '16 at 07:34
  • I also seem to find your answer off. I think the OP is asking about the average performance of linear search: "Will it change when elements (with corresponding probabilities to be searched) are reordered?". Seeing polasairam retracted his answer and comment, I'm the one probably misunderstanding right now. – Czar Pino Mar 01 '16 at 07:40
  • The question isn't about element-access, but about linear search –  Mar 01 '16 at 07:55
  • It was a question in my exam. The exact question has been uploaded in the original post – Sudarshan Sunder Mar 01 '16 at 08:03