我正在一个项目中,我有十个文件,每个文件我必须使用贪婪算法10次。但是,文件具有1000到9000个元素的巨大输入。下面的代码仅是一个包含1000个元素的文件,我运行了10次。我计算平均运行时间和其他2个值,仅一个文件就需要15分钟。通过哪些更改可以使过程更快? (所有代码运行的方法完全没有问题)
public static void main(String[] args) {
long[] avg1=new long[10]; //stores running time of each try in array
long sum=0; //stores average running time
int gval=0;
int optval=0;
for(int i =0;i<10;i++)
{
BuyersList b = new BuyersList();
BuyersList buyers = new BuyersList();
buyers.readFile("src/p500x1000.txt"); //reads file and adds values to list
long start = System.currentTimeMillis();
b=buyers.greedy(500); //algorithm runs
long end = System.currentTimeMillis();
avg1[i]=(end-start); //calculate running time of greedy algorithm
sum+=avg1[i]; //add time of one try to sum
gval=b.totalValue();
optval=buyers.opt;
}
System.out.println("m= 500 :"); // for 500 objects print the values below
System.out.println(" n = 1000 : avgTime = " + sum/10 + " greedy value = " + gval + " opt value = " + optval + " ");
}
贪婪算法:
public BuyersList greedy( int m ) {
if(empty())
{
return null;
}
ItemsList lista = new ItemsList(); // create list of items
BuyerNode current=this.first; // node that represents first buyer
boolean f = true; //suppose one subset list exists
for(int i=0;i<m;i++) //enter pointers of items
{
lista.append(i);
}
BuyersList best = new BuyersList(); //create the returning buyers list
while(f==true) //while one subset list of complete list exists in the list of buyers
{
current=this.maximum(this); //call maximum function to set current to maximum fraction
boolean flag = lista.contains(current.itemsList); // if current's list is a subset
if(flag==true){
best.append(current.id,current.value,current.itemsList); //append current to the best list
lista.remove(current.itemsList); //remove current's list from ItemsList
this.deleteNode(current.id); // call private deletenode function to delete current from buyers
this.nbNodes--;
}
else {this.deleteNode(current.id);}
BuyerNode bnode = this.first;
f = false; //set f to false to exit loop if it doesn't change below
for(bnode=this.first;bnode!=null;bnode=bnode.next)
{
if(lista.contains(bnode.itemsList)) //check if itemslist contains even one buyer subset list
{
f = true; //one subset list exists so loop again
}
}
}
return best;
}