Sorting algorithms/Selection sort

Revision as of 20:37, 21 November 2008 by Lupus (talk | contribs) (Selection sort)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

In this task, the goal is to sort an array (or list) of elements using the Selection sort algorithm. It works as follows: First find the smallest element in the array and exchange it with the element in the first position, then find the second smallest element and exchange it with the element in the second position, and continue in this way until the entire array is sorted. Its asymptotic complexity is O(n2) making it inefficient on large arrays.

Task
Sorting algorithms/Selection sort
You are encouraged to solve this task according to the task description, using any language you may know.

Fortran

Works with: Fortran version 95 and later
PROGRAM SELECTION

  IMPLICIT NONE

  INTEGER :: intArray(10) = (/ 4, 9, 3, -2, 0, 7, -5, 1, 6, 8 /)
 
  WRITE(*,"(A,10I5)") "Unsorted array:", intArray
  CALL Selection_sort(intArray)
  WRITE(*,"(A,10I5)") "Sorted array  :", intArray
   
CONTAINS

  SUBROUTINE Selection_sort(a)
    INTEGER, INTENT(IN OUT) :: a(:)
    INTEGER :: i, minIndex, temp

    DO i = 1, SIZE(a)-1
       minIndex = MINLOC(a(i:), 1) + i - 1
       IF (a(i) > a(minIndex)) THEN
          temp = a(i)
          a(i) = a(minIndex)
          a(minIndex) = temp
       END IF
    END DO
  END SUBROUTINE Selection_sort

END PROGRAM SELECTION

Output

Unsorted array:    4    9    3   -2    0    7   -5    1    6    8
Sorted array  :   -5   -2    0    1    3    4    6    7    8    9