Skip to content

Commit d82a200

Browse files
authored
Add Binary Insertion Sort (TheAlgorithms#3206)
1 parent b36f359 commit d82a200

File tree

2 files changed

+58
-0
lines changed

2 files changed

+58
-0
lines changed
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
package com.thealgorithms.sorts;
2+
public class BinaryInsertionSort{
3+
4+
5+
6+
// Binary Insertion Sort method
7+
public int[] binaryInsertSort(int[] array){
8+
9+
for(int i = 1; i < array.length; i++){
10+
11+
int temp=array[i];
12+
int low = 0;
13+
int high = i - 1;
14+
15+
while(low <= high){
16+
int mid = (low + high) / 2;
17+
if(temp < array[mid]){
18+
high = mid - 1;
19+
}else{
20+
low = mid + 1;
21+
}
22+
}
23+
24+
for(int j = i; j >= low + 1; j--){
25+
array[j] = array[j - 1];
26+
}
27+
28+
array[low] = temp;
29+
}
30+
return array;
31+
}
32+
}
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
package com.thealgorithms.sorts;
2+
import org.junit.jupiter.api.Test;
3+
import static org.junit.jupiter.api.Assertions.*;
4+
5+
6+
7+
class BinaryInsertionSortTest {
8+
BinaryInsertionSort BIS= new BinaryInsertionSort();
9+
10+
@Test
11+
// valid test case
12+
public void BinaryInsertionSortTestNonDuplicate() {
13+
int[] array = {1,0,2,5,3,4,9,8,10,6,7};
14+
int [] expResult= {0,1,2,3,4,5,6,7,8,9,10};
15+
int[] actResult = BIS.binaryInsertSort(array);
16+
assertArrayEquals(expResult,actResult);
17+
}
18+
19+
@Test
20+
public void BinaryInsertionSortTestDuplicate() {
21+
int[] array = {1,1,1,5,9,8,7,2,6};
22+
int [] expResult= {1,1,1,2,5,6,7,8,9};
23+
int[] actResult = BIS.binaryInsertSort(array);
24+
assertArrayEquals(expResult,actResult);
25+
}
26+
}

0 commit comments

Comments
 (0)