2011-04-18 60 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