eli5: pseudo code that performs a binary search

160 views

I’ve only taken beginner python & there’s a lot of advanced answers online

In: 0

2 Answers

Anonymous 0 Comments

Pseudo code is way to write an algorithm without usuing a programming language.

Example :
algorithm that to add 2 numbers
1. Store the first number into a variable A
2. Store the second number into another variable B
3. Add the numbers contained in A and B ans store it to C
4. Print the value of C with a message ” the sum is : ”

To turn this into pseudo code, write it like a program but in simplified english
Start
Initialize A, B, C
A= 10
B = 20
C = A+B
Print the sum is C
Exit

Now algorithm for binary search

1.Input array in ascending or descending order
2.Input number to search
3.find length of the array, assign start as 0 and end of array as length
4. Find middle of the array and store it in variable mid and compare it with the number to search.
5. If the number is bigger than mid, then mid becomes start and end of array remains same
6. Repeat steps 4 and 5 if the middle does not match the number to be searched
7. If middle of the array matches the number then print that it is found.

Now convert these steps into simple english that kinda looks like code. Thats ur pseudo code .

Try it and let me know and ill help u out.. but the pseudo code is left as an exercise. You might have to change the algorithm a bit,

Hint: my algo doesnt not tell me which position in the array the number is stored, thats the next part of the homework

Anonymous 0 Comments

Now this is more psuedo than code but it’s a great explanation of the basic concept behind binary search.

If you’re looking for a specific number in a sorted number book. Go to the center of the book, if your number is smaller than the “middle” number, keep the first half of the book. If your number is larger keep the second half.

Now with the half book, go to the middle of the half book and check the “middle” number. If your number is smaller keep the first half of the half-book, if it’s larger keep the second half of the half-book.

Rinse and repeat.

Eventually you’ll end up with the number you’re looking for (if it exists).