Sorting algorithms/Selection sort: Difference between revisions

From Rosetta Code
Content added Content deleted
m (Fixed code tags)
Line 6: Line 6:


=={{header|Ada}}==
=={{header|Ada}}==
<ada>
<code ada>
with Ada.Text_IO; use Ada.Text_IO;
with Ada.Text_IO; use Ada.Text_IO;


Line 38: Line 38:
end loop;
end loop;
end Test_Selection_Sort;
end Test_Selection_Sort;
</ada>
</code>
Sample output:
Sample output:
<pre>
<pre>
Line 86: Line 86:
=={{header|C}}==
=={{header|C}}==


<c>#include <stdio.h>
<code c>#include <stdio.h>




Line 122: Line 122:
return 0;
return 0;
}</c>
}</code>


Sample output
Sample output
Line 138: Line 138:


=={{header|Forth}}==
=={{header|Forth}}==
<pre>
defer less? ' < is less?
defer less? ' < is less?
: least ( start end -- least )
over cell+ do
i @ over @ less? if drop i then
cell +loop ;
: selection ( array len -- )
cells over + tuck ( end start end )
cell- swap do ( end )
i over least ( end least )
i @ over @ i ! swap !
cell +loop drop ;


: least ( start end -- least )
create array 8 , 1 , 4 , 2 , 10 , 3 , 7 , 9 , 6 , 5 ,
over cell+ do
i @ over @ less? if drop i then
cell +loop ;
: selection ( array len -- )
cells over + tuck ( end start end )
cell- swap do ( end )
i over least ( end least )
i @ over @ i ! swap !
cell +loop drop ;

create array 8 , 1 , 4 , 2 , 10 , 3 , 7 , 9 , 6 , 5 ,
array 10 selection
array 10 selection
array 10 cells dump
array 10 cells dump
</pre>


=={{header|Fortran}}==
=={{header|Fortran}}==
{{works with|Fortran|95 and later}}
{{works with|Fortran|95 and later}}
<code fortran>
PROGRAM SELECTION
PROGRAM SELECTION

IMPLICIT NONE

INTEGER :: intArray(10) = (/ 4, 9, 3, -2, 0, 7, -5, 1, 6, 8 /)
WRITE(*,"(A,10I5)") "Unsorted array:", intArray
IMPLICIT NONE
CALL Selection_sort(intArray)
WRITE(*,"(A,10I5)") "Sorted array :", intArray
INTEGER :: intArray(10) = (/ 4, 9, 3, -2, 0, 7, -5, 1, 6, 8 /)
CONTAINS
WRITE(*,"(A,10I5)") "Unsorted array:", intArray
CALL Selection_sort(intArray)
WRITE(*,"(A,10I5)") "Sorted array :", intArray
CONTAINS
SUBROUTINE Selection_sort(a)
SUBROUTINE Selection_sort(a)
INTEGER, INTENT(IN OUT) :: a(:)
INTEGER, INTENT(IN OUT) :: a(:)
INTEGER :: i, minIndex, temp
INTEGER :: i, minIndex, temp

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

END PROGRAM SELECTION
END PROGRAM SELECTION
</code>
Output
Output:
Unsorted array: 4 9 3 -2 0 7 -5 1 6 8
<pre>
Sorted array : -5 -2 0 1 3 4 6 7 8 9
Unsorted array: 4 9 3 -2 0 7 -5 1 6 8
Sorted array : -5 -2 0 1 3 4 6 7 8 9
</pre>


=={{header|Java}}==
=={{header|Java}}==
This algorithm sorts in place. The call <tt>sort(array)</tt> will rearrange the array and not create a new one.
This algorithm sorts in place. The call <tt>sort(array)</tt> will rearrange the array and not create a new one.
<java>public static void sort(int[] nums){
<code java>public static void sort(int[] nums){
for(int currentPlace = 0;currentPlace<nums.length-1;currentPlace++){
for(int currentPlace = 0;currentPlace<nums.length-1;currentPlace++){
int smallest = Integer.MAX_VALUE;
int smallest = Integer.MAX_VALUE;
Line 205: Line 211:
nums[smallestAt] = temp;
nums[smallestAt] = temp;
}
}
}</java>
}</code>

Revision as of 02:28, 25 January 2009

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

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.

Ada

with Ada.Text_IO; use Ada.Text_IO;

procedure Test_Selection_Sort is

  type Integer_Array is array (Positive range <>) of Integer;
  procedure Sort (A : in out Integer_Array) is
     Min  : Positive;
     Temp : Integer;
  begin
     for I in A'First..A'Last - 1 loop
        Min := I;
        for J in I + 1..A'Last loop
           if A (Min) > A (J) then
              Min := J;
           end if;
        end loop;
        if Min /= I then
           Temp    := A (I);
           A (I)   := A (Min);
           A (Min) := Temp;
        end if;
     end loop;
  end Sort;
  A : Integer_Array := (4, 9, 3, -2, 0, 7, -5, 1, 6, 8);

begin

  Sort (A);
  for I in A'Range loop
     Put (Integer'Image (A (I)) & " ");
  end loop;

end Test_Selection_Sort; Sample output:

-5 -2  0  1  3  4  6  7  8  9

ALGOL 68

Translation of: Ada
Works with: ALGOL 68 version Standard - no extensions to language used
Works with: ALGOL 68G version Any - tested with release mk15-0.8b.fc9.i386
Works with: ELLA ALGOL 68 version Any (with appropriate job cards) - tested with release 1.8.8d.fc9.i386
MODE DATA = REF CHAR;

PROC in place selection sort = (REF[]DATA a)VOID:
BEGIN
   INT min;
   DATA temp;
   FOR i FROM LWB a TO UPB a DO
      min := i;
      FOR j FROM i + 1 TO UPB a DO
         IF a [min] > a [j] THEN
            min := j
         FI
      OD;
      IF min /= i THEN
         temp    := a [i];
         a [i]   := a [min];
         a [min] := temp
      FI
   OD
END # in place selection sort #;
 
[32]CHAR data := "big fjords vex quick waltz nymph";
[UPB data]DATA ref data;  FOR i TO UPB data DO ref data[i] := data[i] OD;
in place selection sort(ref data);
FOR i TO UPB ref data DO print(ref data[i]) OD; print(new line);
print((data))

Output:

     abcdefghiijklmnopqrstuvwxyz
big fjords vex quick waltz nymph

C

#include <stdio.h>


int getminindex(int *a, int s, int b) {

 int i, min=a[s], mi=s;
 for(i=s; i < b; i++)
 {
   if ( a[i] < min ) { min = a[i]; mi = i; }
 }
 return mi;

}

void selectionsort(int *a, int s) {

 int i, t, mi;
 for(i=0; i<s ; i++)
 {
    mi = getminindex(a, i, s);
    t = a[i]; a[i] = a[mi]; a[mi] = t; 
 }

}


int main() {

  int ar[] = { 5, 200, 1, 65, 30, 99, 2, 0 };
  int i;
  
  selectionsort(ar, 8);
  for(i=0; i<8; i++)
  {
    printf("%d\n", ar[i]);
  }
  
  return 0;

}

Sample output

0
1
2
5
30
65
99
200

Forth

defer less?   ' < is less?

: least ( start end -- least )
  over cell+ do
    i @ over @ less? if drop i then
  cell +loop ;
: selection ( array len -- )
  cells over + tuck ( end start end )
  cell- swap do   ( end )
    i over least ( end least )
    i @ over @ i ! swap !
  cell +loop drop ;

create array 8 , 1 , 4 , 2 , 10 , 3 , 7 , 9 , 6 , 5 ,
 
array 10 selection
array 10 cells dump

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

Java

This algorithm sorts in place. The call sort(array) will rearrange the array and not create a new one. public static void sort(int[] nums){ for(int currentPlace = 0;currentPlace<nums.length-1;currentPlace++){ int smallest = Integer.MAX_VALUE; int smallestAt = currentPlace+1; for(int check = currentPlace+1; check<nums.length;check++){ if(nums[check]<smallest){ smallestAt = check; smallest = nums[check]; } } int temp = nums[currentPlace]; nums[currentPlace] = nums[smallestAt]; nums[smallestAt] = temp; } }