Selection Sort: Difference between revisions

From NovaOrdis Knowledge Base
Jump to navigation Jump to search
Line 8: Line 8:


It is an [[Sorting_Algorithms#In-place|in-place]] sorting algorithm.
It is an [[Sorting_Algorithms#In-place|in-place]] sorting algorithm.
<syntaxhighlight lang='java'>
    public void sort(int[] a) {
        if (a.length == 0 || a.length == 1) {
            return;
        }
        for(int i = 0; i < a.length - 1; i ++) {
            int minIndex = i;
            for(int j = i + 1; j < a.length; j ++) {
                if (a[j] < a[minIndex]) {
                    minIndex = j;
                }
            }
            if (i != minIndex) {
                //
                // swap
                //
               
                int tmp = a[i];
                a[i] = a[minIndex];
                a[minIndex] = tmp;
            }
        }
    }
</syntaxhighlight>

Revision as of 21:40, 6 August 2018

Internal

Overview

Selection sort scans the input array from left to right, determining the minimum elements in the subarray spanning from the current position to the end of the input array and then swap the current element with the minimum.

It is an in-place sorting algorithm.

    public void sort(int[] a) {

        if (a.length == 0 || a.length == 1) {

            return;
        }

        for(int i = 0; i < a.length - 1; i ++) {

            int minIndex = i;

            for(int j = i + 1; j < a.length; j ++) {

                if (a[j] < a[minIndex]) {

                    minIndex = j;
                }
            }

            if (i != minIndex) {

                //
                // swap
                //
                
                int tmp = a[i];
                a[i] = a[minIndex];
                a[minIndex] = tmp;
            }
        }
    }