2016-03-08 55 views
-3

我發現它在網絡中,我想知道它的算法的解釋。 我很難理解這一點。非常感謝你:)有人可以解釋這個java程序的算法嗎?

import java.util.Scanner; 
class BinarySearch 
{ 
public static void main(String args[]) 
{ 
int c, first, last, middle, n, search, array[]; 

Scanner in = new Scanner(System.in); 
System.out.println("Enter number of elements"); 
n = in.nextInt(); 
array = new int[n]; 

System.out.println("Enter " + n + " integers"); 


for (c = 0; c < n; c++) 
    array[c] = in.nextInt(); 

System.out.println("Enter value to find"); 
search = in.nextInt(); 

first = 0; 
last = n - 1; 
middle = (first + last)/2; 

while(first <= last) 
{ 
    if (array[middle] < search) 
    first = middle + 1;  
    else if (array[middle] == search) 
    { 
    System.out.println(search + " found at location " + (middle + 1) + "."); 
    break; 
    } 
    else 
    last = middle - 1; 

    middle = (first + last)/2; 
} 
if (first > last) 
    System.out.println(search + " is not present in the list.\n"); 
    } 
} 

我會感謝您的迴應。再次感謝。

+0

這是一個二進制搜索程序,你爲什麼不運行它,看看爲你的自我它做什麼。 –

+0

這是2016年,並且仍然有代碼示例,其中詢問用戶將提供多少條目並且實例化數組來保存它們。 – Neil

回答

-1

二分法搜索算法首先將目標值與排序數組的中間元素的值進行比較。如果目標值等於中間元素的值,則返回該位置並結束搜索。如果目標值小於中間元素的值,則繼續搜索數組的下半部分;或者如果目標值大於中間元素的值,則繼續搜索數組的上半部分。這個過程繼續進行,消除一半元素,並將目標值與剩餘元素的中間元素的值進行比較 - 直到找到目標值(及其相關元素位置返回),或者直到整個陣列具有已被搜索(並返回「未找到」)。

這裏是你的答案精美的解釋:

檢查了這一點 http://www.csit.parkland.edu/~mbrandyberry/CS1Java/Lessons/Lesson27/BinarySearch.htm

+0

它會幫助我很多。謝謝你的回覆:) – Rex

+0

雖然這可能在理論上回答這個問題,[這將是更可取的](/ meta.stackoverflow.com/q/8259)包括答案的基本部分在這裏,並提供鏈接以供參考。 –

+0

你是什麼意思? @Kyll – Rex

相關問題