**Sorting Algorithm Tutorials - Herong's Tutorial Examples** - v6.10, by Dr. Herong Yang

Selection Sort - Java Implementation

This section provides a tutorial on how to implement the Selection Sort algorithm in Java. An implementation diagram is also provided.

Here is my Java implementation of Selection Sort algorithm:

/* HyArrays.java * This class contains sorting methods similar to java.util.Arrays.sort(). * All sorting methods should have a signiture of * %Sort(Object[] a, int fromIndex, int toIndex) * where "fromIndex" is inclusive, and "toIndex" is exclusive. * Copyright (c) HerongYang.com. All Rights Reserved. */ public class HyArrays { public static void selectionSort(HyObject[] a, int fromIndex, int toIndex) { HyObject d; for (int i=fromIndex; i<toIndex; i++) { int k = i; for (int j=i+1; j<toIndex; j++) { if ((a[k]).compareTo(a[j])>0) { k = j; } } d = a[i]; a[i] = a[k]; a[k] = d; } } }

The following diagram illustrates how this implementation works:

-----------29 | 36 39 67 ... 42 | | | | | +-----------+---+---+---+---+---+---+---+-------------------+ | | | | | 4 ... 17 20 24 53----------- | | | | | fromIndex i-1 i k toIndex-1

Note that:

- Elements to be sorted are stored from "fromIndex" to "toIndex-1" inclusive.
- At any given time, elements from "fromIndex" to "i-1" are sorted.
- At any given time, elements from "i" to "toIndex-1" are not sorted.
- As shown in the diagram, the element with the lowerest comparable order is located at "k", which will be placed at the end of the sorted section by swapping it with the element at location "i".

In case you are using older versions of Java that support only the raw "Comparable" interface type, here is my old implementation:

/* HyArraysOld.java * This class contains sorting methods similar to java.util.Arrays. * All sorting methods should have a signature of * %Sort(Object[] a, int fromIndex, int toIndex) * where "fromIndex" is inclusive, and "toIndex" is exclusive. * Copyright (c) HerongYang.com. All Rights Reserved. */ public class HyArrays { public static void selectionSort(Object[] a, int fromIndex, int toIndex) { Object d; for (int i=fromIndex; i<toIndex; i++) { int k = i; for (int j=i+1; j<toIndex; j++) { if (((Comparable)a[k]).compareTo(a[j])>0) { k = j; } } d = a[i]; a[i] = a[k]; a[k] = d; } } }

Table of Contents

Introduction of Sorting Algorithms

Java API for Sorting Algorithms

Insertion Sort Algorithm and Java Implementation

►Selection Sort Algorithm and Java Implementation

Selection Sort - Algorithm Introduction

►Selection Sort - Java Implementation

Selection Sort - Implementation Improvements

Bubble Sort Algorithm and Java Implementation

Quicksort Algorithm and Java Implementation

Merge Sort Algorithm and Java Implementation

Heap Sort Algorithm and Java Implementation

Shell Sort Algorithm and Java Implementation

Sorting Algorithms Implementations in PHP

Sorting Algorithms Implementations in Perl

Sorting Algorithms Implementations in Python