2011-04-18 47 views
1

我有三个数组。我试图通过其中的一种来分类所有这些。所以我的数组是itemarray,pricearray,quantityarray。我希望itemarray进行排序,但相应的数组没有与itemarray一起正确排序。排序数组算法的问题

这是我创建的算法。你知道我该如何解决这个问题?

DO i=1, NumItems-1 

    SmallestItem = MINVAL(itemarray(i:NumItems)) 
    MINLOC_array = MINLOC(itemarray(i:NumItems)) 
    Locationsmallest = (i-1)+MINLOC_array(1) 

    itemarray(Locationsmallest) = itemarray(i) 
    itemarray(i) = SmallestItem 

    pricearray(Locationsmallest) = pricearray(i) 
    pricearray(i) = SmallestItem 

    quantityarray(Locationsmallest) = quantityarray(i) 
    quantityarray(i) = SmallestItem 

END DO 

回答

3

您正在将pricearray(i)设置为来自itemarray的内容。你应该交换pricearray(Locationsmallest)pricearray(i),你可以通过将pricearray(Locationsmallest)的值存储在一个临时变量中来做到这一点。

对于quantityarray(i)也是如此。顺便说一下,这是一个O(n^2)算法,并且当数组中有大量值时,它可能会非常缓慢。

+0

应该临时变量是这样的:pricearray(locationsmallast)= pricesmallestitem我有困难的逻辑。 – EuropaDust 2011-04-18 17:14:33

+1

@EuropaDust:类似于:temp = pricearray(Locationsmallest); pricearray(Locationsmallest)= pricearray(i); pricearray(i)= temp。 (用换行符替换分号)但我承认我不知道Fortran语法,因此您可能需要稍微调整它 – 2011-04-18 21:03:33

+1

即使包含分号,它实际上也是非常好的fortran。 – eriktous 2011-04-18 23:02:40