00001
00012 package sorting;
00013
00014 import java.awt.*;
00015
00022 public class InsertionSort extends Sort
00023 {
00024
00030 protected void doSort()
00031 {
00032 int pos;
00033 for (int i = 1; i <= theArray.length - 1; i++)
00034 {
00035 pos = binsearch(theArray, 0, i - 1, theArray[i]);
00036 move(i, pos, theArray);
00037 this.showArray();
00038 this.theLabel.setText(this.calcRuntime()+"ms");
00039 this.theLabel.validate();
00040 }
00041 }
00042
00043 private void move(int i, int j, int[] a)
00044 {
00045 int tmp = a[i];
00046 for (int g = i; g >= j + 1; g--)
00047 {
00048 a[g] = a[g - 1];
00049 }
00050 a[j] = tmp;
00051 }
00052
00059 private int binsearch(int[] a, int low, int high, int x)
00060 {
00061 int middle = 0;
00062 while (low <= high)
00063 {
00064 middle = (low + high) / 2;
00065 if (a[middle] == x) return middle;
00066 else if (a[middle] < x) low = middle + 1;
00067 else if (a[middle] > x) high = middle - 1;
00068 }
00069 return low;
00070 }
00071
00072 }