정수 대신 문자열을 사용하는 이진 검색 프로그램을 설정하려고합니다. 문제는 문자열 값보다 적은 수의 배열을 만드는 방법을 모르겠다는 것입니다. 문자열 값보다다른 요소보다 적은 요소를 찾는 방법은 무엇입니까?
문자열 배열 이하 예컨대
.
/**
The StringBinarySearcher class provides a public static
method for performing a binary search on an String array.
*/
public class StringBinarySearcher
{
/**
The search method performs a binary search on an String
array. The array is searched for the number passed to
value. If the number is found, its array subscript is
returned. Otherwise, -1 is returned indicating the
value was not found in the array.
@param numbers The array to search.
@param value The value to search for.
*/
public static int search(String[] numbers, String value)
{
int first; // First array element
int last; // Last array element
int middle; // Mid point of search
int position; // Position of search value
boolean found; // Flag
// Set the inital values.
first = 0;
last = numbers.length - 1;
position = -1;
found = false;
// Search for the value.
while (!found && first <= last)
{
// Calculate mid point
middle = (first + last)/2;
// If value is found at midpoint...
if (numbers[middle] == value)
{
found = true;
position = middle;
}
// else if value is in lower half...
// needs array to be less then the string value?, without using equality regulators
else if (numbers[middle].compareTo(numbers[middle +1]) > 0)
last = middle - 1;
// else if value is in upper half....
else
first = middle + 1;
}
// Return the position of the item, or -1
// if it was not found.
return position;
}
}
왜 문자열 배열에서 이진 검색을 수행하려면 숫자 배열이 필요하다고 생각하십니까? –
BTW,'if (numbers [middle] == value)'가 잘못 비교 된 경우'if (numbers [middle] .equals (value)) '를 사용하십시오. – MByD
정수가 아닌 숫자로 정수를 정렬 할 수 있습니까? – user663428