Welcome to Sort and search arrays in C / C++ - PART 3
Today I wanted to focus my attention on the searching algorithm. Let's find some integers!
First I will start with the most simple implementation which brute-force iterates through each integer until it finds what it wants.
The code to do this is super simple....
Even though this is not efficient, it is still ridiculously fast, this is because generally the slowest operations are data manipulation. Newer CPU's are fantastic at prefetching steams of data by using branch prediction. If you are not familiar with branch prediction, I really suggest you go search and have a read about how it works.
Regardless, we want to optimise our function, so we will again be using divide and conquer.
First I wanted to give an example of partitioning, this method would be faster than our original but it is completely pointless.
I just wanted to show what is the point of partitioning. Here we can see depending on the middle value of our array, we will search either the lower or the upper half of the array. So with divide and conquer what we want to achieve is to keep dividing the array by the divided (or middle) index.
Writing such a function is actually even more simple than this indexof2 function.
I have commented the code step by step. This is one of the most easiest indexof functions to write.
I have updated the original code main function to run the dac index of 20 times.
After I finished writing this dac index function, I done some searching to see if anyone had divised a better way of doing it, but it seems this is considered the best way of doing it.
I wanted to just add that an unsorted array, you could only use the linear indexof, however, we could slightly improve this function by removing the count index comparison.
When declaring our array, we add an additional array entry at the end (This could be modified to work with multi threaded read access to the array)
So we update our main to be like so:
Notice our declaration has +1 for an additional array that won't be filled or used in general, except for our linear index of.
So this version of the indexof will save 1 compare instruction per array item at the cost of 1 mov and a cmp at the end.
And on that note, I will wrap this post up with the full code we have so far.
As I noted in the previous article on this subject, I will probably convert this into a c++ library for re-usability and will add sorting of different types of data.
Until next time.....