2018년 6월 20일 수요일

Sorting of an array in FORTAN (using MINLOC)

There is no intrinsic sorting function in FORTAN.
Though it is easy to write a sorting program by using various sorting algorithm
or import the exising codes from internet,
one of the simple method is to use MINLOC intrinsic function in FORTRAN.
(Though it may be not an efficient one, it is short.)

Suppose there is an array size N, narray(1:N). Then, one can sort the array by

Do i=1,N
  l = MINLOC(narray(i:N),1)
  temp = narray(i)
  narray(i)=narray(i+l-1)
  narray(i+l-1)= temp
End do

Now, narray(1:N) is sorted by its values.

If one want to keep track of original index, prepare another array, index(1:N).

Do i=1,N
 index(i)=i
End Do
Do i=1,N
  l = MINLOC(narray(i:N),1)
  temp = narray(i)
  narray(i)=narray(i+l-1)
  narray(i+l-1)= temp
  temp=index(i) 
  index(i)=index(i+l-1)
  index(i+l-1)=temp
End do

Now, index(1:N) is the index in original array.


댓글 없음:

댓글 쓰기