MHB Algorithm with time complexity o(n^2)

AI Thread Summary
The discussion centers on developing an efficient algorithm to find two elements in a set of real numbers that have the minimum absolute difference, with a time complexity of less than O(n^2). The proposed solution involves first sorting the set using heapsort, which has a time complexity of O(n log n), followed by a single pass through the sorted list to find the minimum difference between consecutive elements. This approach effectively reduces the overall complexity to O(n log n), which meets the requirement of being less than O(n^2). The participants also discuss the correctness of the algorithm, suggesting that induction could be used to prove its validity. The focus remains on optimizing the algorithm while ensuring its correctness.
evinda
Gold Member
MHB
Messages
3,741
Reaction score
0
Hi! (Smile)

I am looking at the following exercise:

Let $M=\{ y_1, y_2, \dots, y_n \}$ a set of real numbers, where $n \geq 2$. Describe an algorithm, that has time complexity $o(n^2)$ and that finds and returns two elements $y_k$ and $y_l$ of $M$, such that:

$$|y_k-y_l|=\min_{1 \leq i,j \leq n} |y_i-y_j|$$I think that we cannot do this with the use of two while loops, because the time complexity will be $\leq cn^2$, but we want it to be $<cn^2$, or am I wrong? (Thinking)
How else could we do this? (Worried)
 
Technology news on Phys.org
First sort the values (with say heap sort) of time complexity $n\ln\,n$. Then in the sorted list find the desired elements in one pass of the n elements. Total complexity "little oh" $n^2$.
 
johng said:
First sort the values (with say heap sort) of time complexity $n\ln\,n$. Then in the sorted list find the desired elements in one pass of the n elements. Total complexity "little oh" $n^2$.

So, is it right like that? (Thinking)

Code:
Heapsort(A){
  Buildheap(A);
  for (i=size(A); i>1; --i){
       swap(A[i],A[1]);
       heap_size(A)=heap_size(A)-1;
       Heapify(A,1);
   }
}
 
Elements(S,n){
  int i,min,k;
  Heapsort(S)
  min=abs(S[1]-S[2]);
  for (i=2; i<n; i++){ 
      if (abs(S[i]-S[i+1])<min)
          min=abs(S[i]-S[i+1]);
          k=i;
  }
  return S[k],S[k+1];
}
 
Looks right to me.
 
How could we show the correctness of the algorithm?
Could we prove that it is correct, using induction on [m] i [/m] ?
 
Thread 'Is this public key encryption?'
I've tried to intuit public key encryption but never quite managed. But this seems to wrap it up in a bow. This seems to be a very elegant way of transmitting a message publicly that only the sender and receiver can decipher. Is this how PKE works? No, it cant be. In the above case, the requester knows the target's "secret" key - because they have his ID, and therefore knows his birthdate.
Back
Top