Skip to content

Instantly share code, notes, and snippets.

@zeraf29
Last active March 1, 2017 13:50
Show Gist options
  • Save zeraf29/3308fbcee77fb25f12d783eeae74e59c to your computer and use it in GitHub Desktop.
Save zeraf29/3308fbcee77fb25f12d783eeae74e59c to your computer and use it in GitHub Desktop.
자바스크립트를 이용한 배열 내 요소 검색 이진검색 함수(칸 아카데미 응용: 이진검색 내용)
/*하위 내용은 칸 아카데미-알고리즘 강의 내 이진 검색 부분의 퀴즈 내용을 정리한
* https://ko.khanacademy.org/computing/computer-science/algorithms/binary-search/e/running-time-of-binary-search
*Below source is a way by me about Khan academy.org 's algorithms-binary search quiz
*/
/* Returns either the index of the location in the array,
or -1 if the array did not contain the targetValue */
var doSearch = function(array, targetValue) {
var min = 0;
var max = array.length - 1;
var guess;
var guessTotal=0;
while(max>=min){
guess = Math.floor((max+min)/2);
guessTotal++;
println("Now guess index: " + guess+"@"+array[guess]);
if(array[guess]===targetValue){
println(guessTotal);
return guess;
}
else if(array[guess]<targetValue){min=guess+1;}
else{max=guess-1;}
}
return -1;
};
var primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37,
41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97];
var result = doSearch(primes, 73);
println("Found prime at index " + result);
Program.assertEqual(doSearch(primes, 73), 20);
Program.assertEqual(doSearch(primes, 5), 2);
Program.assertEqual(doSearch(primes, 83), 22);
@zeraf29
Copy link
Author

zeraf29 commented Feb 26, 2017

  1. 추측한 guess값 출력
  2. 총 추측 개수 출력
    3.추가 테스트 함수 호출

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment