InsertionSort.java

  1. /*
  2.  * Copyright 2024 Hochschule Luzern Informatik.
  3.  *
  4.  * Licensed under the Apache License, Version 2.0 (the "License");
  5.  * you may not use this file except in compliance with the License.
  6.  * You may obtain a copy of the License at
  7.  *
  8.  *      http://www.apache.org/licenses/LICENSE-2.0
  9.  *
  10.  * Unless required by applicable law or agreed to in writing, software
  11.  * distributed under the License is distributed on an "AS IS" BASIS,
  12.  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13.  * See the License for the specific language governing permissions and
  14.  * limitations under the License.
  15.  */
  16. package ch.hslu.exercises.sw11.ex1.n41.array.sort;

  17. public final class InsertionSort {

  18.     /**
  19.      * Privater Konstruktor.
  20.      */
  21.     private InsertionSort() {
  22.     }

  23.     /**
  24.      * Sortiert das int-Array aufsteigend. Zur Anwendung kommt der
  25.      * Sortieralgorithmus "direktes Einfügen".
  26.      *
  27.      * @param array Interger-Array.
  28.      * @param min   der Index des ersten zu sortierenden Elements
  29.      *              (einschliesslich).
  30.      * @param max   der Index des letzten exklusiven Elements, das sortiert werden
  31.      *              soll.
  32.      */
  33.     public static void exec(final int[] array, final int min, final int max) {
  34.         int elt;
  35.         int j;

  36.         for (int i = min; i < max; i++) {
  37.             elt = array[i];      // next elt for insert
  38.             j = i;               // array[min]..array[j-1] already sorted
  39.             while ((j > min) && (array[j - 1] > elt)) {
  40.                 array[j] = array[j - 1]; // shift right
  41.                 j--;             // go further left
  42.             }
  43.             array[j] = elt;      // insert elt
  44.         }                        // array[min]...array[max-1] sorted
  45.     }

  46. }