Selection Sort: Difference between revisions

From NovaOrdis Knowledge Base
Jump to navigation Jump to search
 
(One intermediate revision by the same user not shown)
Line 4: Line 4:


=Overview=
=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 [[Sorting_Algorithms#In-place|in-place]] sorting algorithm.
It is an [[Sorting_Algorithms#In-place|in-place]] sorting algorithm.
Line 11: Line 9:
The best case and the worst case running time are both Θ(n<sup>2</sup>).
The best case and the worst case running time are both Θ(n<sup>2</sup>).


<syntaxhighlight lang='java'>
=Algorithm=
    public void sort(int[] a) {


        for(int i = 0; i < a.length - 1; i ++) {
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.  


            int minIndex = i;
<syntaxhighlight lang='java'>
 
public void sort(int[] a) {
            for(int j = i + 1; j < a.length; j ++) {
  for(int i = 0; i < a.length - 1; i ++) {
 
    int minIndex = i;
                if (a[j] < a[minIndex]) {
    for(int j = i + 1; j < a.length; j ++) {
 
      if (a[j] < a[minIndex]) {
                    minIndex = j;
        minIndex = j;
                }
      }
            }
    }
 
    if (i != minIndex) {
            if (i != minIndex) {
      //
 
      // swap
                //
      //
                // swap
      int tmp = a[i];
                //
      a[i] = a[minIndex];
               
      a[minIndex] = tmp;
                int tmp = a[i];
                a[i] = a[minIndex];
                a[minIndex] = tmp;
            }
        }
     }
     }
  }
}
</syntaxhighlight>
</syntaxhighlight>

Latest revision as of 22:07, 9 October 2021

Internal

Overview

It is an in-place sorting algorithm.

The best case and the worst case running time are both Θ(n2).

Algorithm

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.

public void sort(int[] a) {
  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;
    }
  }
}