Home > IB Computer Science 2014 > Selection Sort

Selection Sort

Video

http://youtu.be/TAWyTkpV9DE

Pseudocode implementation

selectionSort(ARRAY)
  loop I from 0 to ARRAY.length - 2
    MIN = I
    loop J from I to ARRAY.length - 1
      if ARRAY[J] < ARRAY[MIN] then
        MIN = J
      end if
    end loop
    if MIN != I then
      TMP = ARRAY[I]
      ARRAY[I] = ARRAY[MIN]
      ARRAY[MIN] = TMP
    end if
end loop
end

Java implementation

public class SelectionSort {

    int[] arry = {2, 5, 8, 3, 1, 4, 6, 7};
    int min;
    int tmp;

    public static void main(String[] args) {
        SelectionSort s = new SelectionSort();
        s.go();
        s.write();
    }

    void go() {

        for (int k = 0; k < arry.length - 1; k++) {
            min = k;
            for (int i = k; i < arry.length; i++) {
                if (arry[i] < arry[min]) {
                    min = i;
                }
            }
            tmp = arry[min];
            arry[min] = arry[k];
            arry[k] = tmp;
        }
    }

    void write() {
        for (int i = 0; i < arry.length; i++) {
            System.out.println(arry[i]);
        }
    }
}
Advertisements
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s