Binary search · การค้นหาแบบทวิภาคี
Binary search
The array is sorted. Return the index of target, or -1 if it isn't there. Binary search halves the range each step: check the middle element, then keep looking in just the left or right half. Far faster than scanning every element.
การค้นหาแบบทวิภาค
อาร์เรย์นี้ถูก เรียงลำดับ แล้ว กลับค่าดัชนีของ target หรือ -1 ถ้ามันไม่อยู่ในนั้น การค้นหาแบบทวิภาค (Binary search) จะแบ่งช่วงครึ่งหนึ่งทุกขั้นตอน: ตรวจสอบองค์ประกอบตรงกลาง แล้วมองหาต่อในครึ่งซ้ายหรือครึ่งขวาเพียงอย่างเดียว เร็วกว่ามากเมื่อเทียบกับการสแกนทุกองค์ประกอบ
Complete binarySearch(int[] a, int target) for a sorted array a: return the index of target, or -1 if absent. Use binary search. · เติม binarySearch(int[] a, int target) สำหรับเรียงลำดับ-array a: กลับค่าดัชนีของ target หรือ -1 หากไม่พบ ใช้ binary search
Click Run to see the output here. · คลิก Run เพื่อดูผลลัพธ์ที่นี่