Skip to content

Commit

Permalink
Implementation of ternary search
Browse files Browse the repository at this point in the history
  • Loading branch information
singloon committed Oct 27, 2020
1 parent f497729 commit 7e74ec4
Show file tree
Hide file tree
Showing 3 changed files with 92 additions and 0 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
# IDE file
build/
.idea/
*.iml

# gradle directory
.gradle/
Expand Down
43 changes: 43 additions & 0 deletions src/main/java/com/ordestiny/tdd/algorithms/TernarySearch.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
package com.ordestiny.tdd.algorithms;

public class TernarySearch {
public int search(int[] array, int searchNumber) {
if (!isSorted(array)) {
throw new IllegalArgumentException();
}

int low = 0;
int high = array.length - 1;

while (high >= low) {
int mid1 = low + (high - low) / 3;
int mid2 = high - (high - low) / 3;

if (array[mid1] == searchNumber) {
return mid1;
}

if (array[mid2] == searchNumber) {
return mid2;
}

if (searchNumber > array[mid2]) {
low = mid2 + 1;
} else if (searchNumber < array[mid1]) {
high = mid1 - 1;
} else {
low = mid1 + 1;
high = mid2 - 1;
}
}
return -1;
}

private boolean isSorted(int[] array) {
for (int i = 0; i < array.length - 1; i++) {
if (array[i] > array[i + 1])
return false;
}
return true;
}
}
48 changes: 48 additions & 0 deletions src/test/java/com/ordestiny/tdd/algorithms/TernarySearchTest.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
package com.ordestiny.tdd.algorithms;

import org.junit.jupiter.api.Test;

import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;

public class TernarySearchTest {
private final TernarySearch underTest = new TernarySearch();

@Test
public void shouldReturnIndexWhenLowerThird() {
assertThat(underTest.search(new int[]{1,2,3,4,5,6,7,8,9,10}, 4)).isEqualTo(3);
}

@Test
public void shouldReturnIndexWhenUpperThird() {
assertThat(underTest.search(new int[]{1,2,3,4,5,6,7,8,9,10}, 7)).isEqualTo(6);
}

@Test
public void shouldReturnIndexUpper() {
assertThat(underTest.search(new int[]{1,2,3,4,5,6,7,8,9,10}, 8)).isEqualTo(7);
}

@Test
public void shouldReturnIndexLower() {
assertThat(underTest.search(new int[]{1,2,3,4,5,6,7,8,9,10}, 1)).isEqualTo(0);
}

@Test
public void shouldReturnIndexBetween() {
assertThat(underTest.search(new int[]{1,2,3,4,5,6,7,8,9,10}, 5)).isEqualTo(4);
}

@Test
public void shouldReturnMinusOneWhenNoMatch() {
assertThat(underTest.search(new int[]{1,2,3,4,5,6,7,8,9,10}, 11)).isEqualTo(-1);
}

@Test
public void shouldThrowExceptionWhenNotSorted() {
assertThatThrownBy(() -> underTest.search(new int[]{10, 9}, 11))
.isExactlyInstanceOf(IllegalArgumentException.class);
}


}

0 comments on commit 7e74ec4

Please sign in to comment.