Programming a binary search algorithm

My newest software engineering project consisted of writing a program that would write a binary search algorithm. In my previous project, I had mentioned that I avoided using arrays, but in this project I had to use arrays. An array is an arrangement of objects, but in this case it would be an arrangement of integers. The binary search function should look into the array and find the index where the value is being held.

For this project I decided to take an extra step. I was to assume that the data pool size was given and the data was sorted. However I took the approach to figure out how to dynamically allocate an array in my C programming course during run-time. This means, that the program would ask the user for the size of the array, rather than having a fixed sized. This part wasn’t too difficult. I needed to allocate space in the computer’s memory in order to be able to create an array that will fit in the allocated memory.

So now that I’ve set up my array at run-time, I now gave the user the option to enter the data pool. However I had to make sure that the data was sorted, as the user may input the data in no specific order. This was tricky, as I have not worked with arrays before, I searched online on how to sort arrays, and I found out a sorting technique called bubble sort. Bubble sorting consists of looking through the array and comparing adjacent value and swapping them if they are in wrong order. This type of sorting is somewhat slow, but in my case, I’m not expecting to sort throw large pool of data. Great, so now I have established my dynamic array and I have sorted the array, now I can focus on writing the binary search algorithm.

The idea behind the binary search algorithm or half-interval search algorithm is to compare two values (the first index and last index) to the middle index of the array, if the values are equal, there value has been found, if not, it will take a new set of values and compare the middle index again until the values are equal. The comparison is done with by size comparison, is the middle index greater than or less than the search query.  For this part I tried a few methods and I wasn’t getting quiet what I was expected, so what I decided to do, was to visually see how the algorithm worked and for that I did an example on paper and pen. After I saw what actually needs to happen, I could then write the algorithm so replicate that process. I found out that writing the algorithm down in paper helped a lot as I was able to solve the algorithm after 1 single try after writing it down, in comparison with 2 of my previous failures of just thinking of the algorithm.  This is how I went about completing my software engineering project for my C Programming course. I enjoyed working on this project mainly because I did most of the work without getting extra help

-Jared D.

Tags: , ,

Comments are closed.