Compare commits

...

2 Commits

Author SHA1 Message Date
wangsiyuan 35e5acb50f Update BinarySearchTest.java 2024-07-10 00:31:05 +08:00
wangsiyuan 4f478c08ac Update BinarySearch.java 2024-07-10 00:31:03 +08:00
2 changed files with 60 additions and 7 deletions

View File

@ -1,5 +1,4 @@
package com.nbee.solution.practice;
class BinarySearch {
public static int binarySearchBasic(int[] nums, int target){
int i = 0 ,j = nums.length - 1;//设置指针和初始值
@ -17,10 +16,28 @@ class BinarySearch {
}
}
return -1;
/**
* i<=j?
* 使 i <= j
* i < j i j
*/
}
public static int binarySearchAlternative(int[] nums, int target){
int i = 0 ,j = nums.length;
while (i < j){
int m = (i + j) >>> 1;
if (target < nums[m]){
j = m;
}
else if (nums[m] < target){
i = m + 1;
}
else {
return m;
}
}
return -1;
}
/**
* i<=j?
* 使 i <= j
* i < j i j
*/
}

View File

@ -2,12 +2,14 @@ package com.nbee.solution.practice;
import org.junit.Assert;
import org.junit.Test;
import static org.junit.jupiter.api.Assertions.*;
public class BinarySearchTest {
private int[] nums = {1, 3, 5, 7, 9};
@Test
public void testBinarySearchBasic_Found() {
int[] nums = {1, 3, 5, 7, 9};
int[] nums = {1, 3, 5, 7, 9, 11, 13};
int target = 5;
int result = BinarySearch.binarySearchBasic(nums, target);
Assert.assertEquals("Element should be found at index 2", 2, result);
@ -48,4 +50,38 @@ public class BinarySearchTest {
int result = BinarySearch.binarySearchBasic(nums, target);
Assert.assertEquals("Binary search should work on decreasing arrays", 2, result);
}
@Test
public void testBinarySearchAlternativeFound() {
// Test that the method correctly returns the index of an existing element
int target = 7;
int result = BinarySearch.binarySearchAlternative(nums, target);
assertEquals(3, result, "The target should be found at index 3");
}
@Test
public void testBinarySearchAlternativeNotFound() {
// Test that the method correctly returns -1 when the element is not present
int target = 4;
int result = BinarySearch.binarySearchAlternative(nums, target);
assertEquals(-1, result, "The target should not be found");
}
@Test
public void testBinarySearchAlternativeWithEmptyArray() {
// Test with an empty array
int[] emptyNums = new int[]{};
int target = 1;
int result = BinarySearch.binarySearchAlternative(emptyNums, target);
assertEquals(-1, result, "The target should not be found in an empty array");
}
@Test
public void testBinarySearchAlternativeWithSingleElement() {
// Test with a single element array
int[] singleNums = new int[]{5};
int target = 5;
int result = BinarySearch.binarySearchAlternative(singleNums, target);
assertEquals(0, result, "The target should be found at index 0 in a single-element array");
}
}