Permalink
Browse files

add selectionSort() and insertionSort()

  • Loading branch information...
1 parent 6051ba2 commit 5b8507d2462aa662ea9e20d972f3a24f7e799b36 @philipjkim committed Apr 2, 2012
@@ -11,7 +11,7 @@
*/
public class SortableArray {
- boolean logEnabled = true;
+ boolean logEnabled = false;
private long[] backingArray;
private int nElems;
@@ -56,6 +56,38 @@ private void swap(long[] backingArray, int idx1, int idx2) {
backingArray[idx2] = temp;
}
+ public void selectionSort() {
+ log("Unsorted : " + this.toString());
+ for (int out = 0; out < nElems - 1; out++) {
+ int minIndex = out;
+ for (int in = out + 1; in < nElems; in++) {
+ if (backingArray[minIndex] > backingArray[in])
+ minIndex = in;
+ }
+ if (out != minIndex) {
+ swap(backingArray, out, minIndex);
+ log("Swapped : " + this.toString());
+ }
+ }
+ log("Sorted : " + this.toString());
+ }
+
+ public void insertionSort() {
+ log("Unsorted : " + this.toString());
+ for (int out = 1; out < nElems; out++) {
+ long toBeInserted = backingArray[out];
+ int in = out;
+ while (in > 0 && backingArray[in - 1] > toBeInserted) {
+ backingArray[in] = backingArray[in - 1];
+ log("Shifted : " + this.toString());
+ in--;
+ }
+ backingArray[in] = toBeInserted;
+ log("Inserted : " + this.toString());
+ }
+ log("Sorted : " + this.toString());
+ }
+
@Override
public String toString() {
StringBuffer sb = new StringBuffer();
@@ -31,4 +31,28 @@ public void bubbleSort() {
// then
assertThat(array.toString(), is("1 2 3 4 5 "));
}
+
+ @Test
+ public void selectionSort() {
+ // given
+ assertThat(array.toString(), is("5 4 3 2 1 "));
+
+ // when
+ array.selectionSort();
+
+ // then
+ assertThat(array.toString(), is("1 2 3 4 5 "));
+ }
+
+ @Test
+ public void insertionSort() {
+ // given
+ assertThat(array.toString(), is("5 4 3 2 1 "));
+
+ // when
+ array.insertionSort();
+
+ // then
+ assertThat(array.toString(), is("1 2 3 4 5 "));
+ }
}

0 comments on commit 5b8507d

Please sign in to comment.