**Sorting Algorithm Tutorials - Herong's Tutorial Examples** - Version 6.01, 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. * 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) 2011 by Dr. Herong Yang, herongyang.com */ 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; } } }

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

- 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".

*Last update: 2011.*

Table of Contents

Introduction of Sorting Algorithms

Java API for Sorting Algorithms

Insertion Sort Algorithm and Implementation

►Selection Sort Algorithm and Implementation

Selection Sort - Algorithm Introduction

►Selection Sort - Java Implementation

Selection Sort - Implementation Improvements

Bubble Sort Algorithm and Implementation

Quicksort Algorithm and Implementation

Merge Sort Algorithm and Implementation

Heap Sort Algorithm and Implementation

Shell Sort Algorithm and Implementation