Help please Consider the following algorithm for finding the distance between th
ID: 3784939 • Letter: H
Question
Help please
Consider the following algorithm for finding the distance between the two closest elements in an array of numbers. Algorithm MinDistance(A[0. .n - 1])//Input: Array A[0.. n -1] of numbers//Output: Minimum distance between two of its elements d min leftarrow infinity for i leftarrow 0 to n - 1 do for j leftarrow0 to n - 1 do if i _= j and |A[i] - A[j]| lessthan dmin dmin leftarrow |A[i] ? A[j]| return dmin Make as many improvements as you can in this algorithmic solution to the problem. (If you need to, you may change the algorithm altogether: if not, improve the implementation given.)Explanation / Answer
Algorithm MinDistance(A[0...n-1])
//Input: Array A[0...n-1] of numbers
// output: Minimum distance netween two of its elements.
dmin<-MAX element from array
for i<- 0 to n-1 do
for j<- 0 to n-1 do
if i != j and (a[i]-a[j])<dmin
dmin <- (A[i]-A[j])
return dmin
There are 2 changes that i made first id dmin should be assigned maximum element in array initially because the diff cannot be greater then the max element of the array and the second change in the array in the if condition that is if i !=j because if they are same then it it will point to the same element and the diffrence will become 0 and this is not correct .
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.