Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chris Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

how to sort 2 columns together?

Status
Not open for further replies.

Ahn210

Technical User
Jun 18, 2013
11
Hello,

I'm a newbie to fortran and need some help on sorting 2 columns of data (related) to be sorted on 1 column.
For instance, if my input text file has following:

ID nums
12 0.111
58 1.52
101 0.5
10 2.89

I declared 2 single array ID:)) and nums:))
and applied selection sort on nums:))

DO J = 1, 9
DO K = J+1, 10
IF(nums(J) > nums(K)) THEN
temp = nums(K)
nums(K) = nums(J)
nums(J) = temp
END IF
END DO
END DO

result was it only sorted on nums and misaligned data with ID....

How can I sort for following outcome?
ID nums
101 0.5
12 0.111
58 1.52
10 2.89

Thank you!










 
when you do this:
Code:
temp = nums(K)
nums(K) = nums(J)
nums(J) = temp
also do this
Code:
temp = ID(K)
ID(K) = ID(J)
ID(J) = temp
 
Alternatively create a type and sort on members of the type.
 
Alternatively, build an integer array which will contains the ordering. In that case, you don't have to sort neither nums nor ID :

Code:
INTEGER :: order(10) 

DO i=1,10
  order(i)=i
ENDDO

DO J = 1, 9
  DO K = J+1, 10
    IF(nums(order(J)) > nums(order(K))) THEN
      temp = order(K)
      order(K) = order(J)
      order(J) = temp
    END IF
  END DO 
END DO 

DO J=1,10
  WRITE(*,*) ID(order(j)),nums(order(j))
ENDDO

At last, notice that your sorting algorithm is simple but very weak... Use it only for arrays with a small size (< 100).

François Jacq
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top