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

Last update: 2011.

Table of Contents

 About This Book

 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 - Performance

 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

 Performance Summary of Java Implementations

 References

 PDF Printing Version