所以我从我购买的这本书中自学了算法,并且我有一个伪代码,用于查找数字数组中两个最简洁元素之间的距离
MinDistance(a[0...n-1])
Input: Array A of numbers
Output: Minimum Distance between two of its elements
dMin <- maximum integer
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
Run Code Online (Sandbox Code Playgroud)
但是,我想对这个算法解决方案进行改进.改变已经存在的东西,或者一起重写.有人可以帮忙吗?我用Java编写函数和类来测试伪代码?那是对的吗?再一次,我怎样才能从效率的角度来改善它.
//Scanner library allowing the user to input data
import java.lang.Math.*;
public class ArrayTester{
//algorithm for finding the distance between the two closest elements in an array of numbers
public int MinDistance(int [] ar){
int [] a = ar;
int aSize = a.length;
int dMin = 0;//MaxInt
for(int i=0; i< aSize; i++)
{
for(int j=i+1; j< aSize;j++)
{
dMin = Math.min(dMin, Math.abs( a[i]-a[j] );
}
}
return dMin;
}
//MAIN
public static void main(String[] args){
ArrayTester at = new ArrayTester();
int [] someArray = {9,1,2,3,16};
System.out.println("NOT-OPTIMIZED METHOD");
System.out.println("Array length = "+ someArray.length);
System.out.println("The distance between the two closest elements: " + at.MinDistance(someArray));
} //end MAIN
} //END CLASS
Run Code Online (Sandbox Code Playgroud)
所以我更新了函数以最小化调用Math.abs两次.我还能做些什么呢?如果我要用sort重写它,它会改变我的for循环吗,或者它会在理论上运行得更快.
public int MinDistance(int [] ar){
int [] a = ar;
int aSize = a.length;
int dMin = 0;//MaxInt
for(int i=0; i< aSize; i++)
{
for(int j=i+1; j< aSize;j++)
{
dMin = Math.min(dMin, Math.abs( a[i]-a[j] );
}
}
return dMin;
}
Run Code Online (Sandbox Code Playgroud)
Jon*_*eet 12
一个明显的效率改进:首先排序整数,然后你可以查看相邻的整数.任何数字都将最接近其邻居向上或向下.
这将复杂性从O(n 2)改变为O(n log n).不可否认的是,n显示的小值不会产生显着差异,但就理论复杂性而言,它很重要.
您可能想要进行一次微优化:使用局部变量来存储结果Math.abs,如果结果小于最小值,则无需重新计算.或者,您可能想要使用dMin = Math.min(dMin, Math.abs(a[i] - a[j])).
请注意,您需要注意边界条件 - 如果您允许负数,则减法可能会溢出.