DEV Community

Fabrizio Bagalà
Fabrizio Bagalà

Posted on • Edited on

Fibonacci Search

Another interesting search algorithm is Fibonacci search. It exploits the Fibonacci sequence to find an item in an ordered list. This algorithm iteratively divides the input array into subsections, similar to binary search. However, unlike the latter, the array is divided into unequal parts, making it more efficient for large data sets.

Fibonacci sequence

The Fibonacci sequence is a series of numbers where each number is the sum of the two preceding ones. It starts with 0 and 1, and from there each subsequent number is the sum of the two preceding ones. So, the sequence starts like 0, 1, 1, 2, 3, 5, 8, 13, 21, and so on.

How it works

The Fibonacci search algorithm starts by generating the smallest Fibonacci number that is greater than or equal to the size of the array being searched. This Fibonacci number, F, becomes the starting point for the search.

The algorithm then compares the element being searched for with the element in the array at the position of the (F-2)th Fibonacci number. If the element being searched for is larger, the algorithm excludes the first F-2 elements and repeats the process on the remaining array. If the element being searched for is smaller, it excludes the last F-1 elements and repeats the process on the remaining array.

This process repeats, with the algorithm continuing to "remove" portions of the array until the searched-for element is found, or until the array has been fully explored.

public static class SearchAlgorithms
{
    public static int FibonacciSearch(int[] arr, int x)
    {
        var fibMMm2 = 0; // (m-2)'th Fibonacci No.
        var fibMMm1 = 1; // (m-1)'th Fibonacci No.
        var fibM = fibMMm2 + fibMMm1; // m'th Fibonacci
        var n = arr.Length;

        while (fibM < n)
        {
            fibMMm2 = fibMMm1;
            fibMMm1 = fibM;
            fibM = fibMMm2 + fibMMm1;
        }

        var offset = -1;

        while (fibM > 1)
        {
            var i = Math.Min(offset + fibMMm2, n - 1);

            if (arr[i] < x)
            {
                fibM = fibMMm1;
                fibMMm1 = fibMMm2;
                fibMMm2 = fibM - fibMMm1;
                offset = i;
            }
            else if (arr[i] > x)
            {
                fibM = fibMMm2;
                fibMMm1 -= fibMMm2;
                fibMMm2 = fibM - fibMMm1;
            }
            else
            {
                return i;
            }
        }

        return fibMMm1 == 1 && arr[offset + 1] == x ? offset + 1 : -1;
    }
}
Enter fullscreen mode Exit fullscreen mode

Time complexity

The time complexity is O(log n) because, with each comparison, the algorithm reduces the size of the search space by about a factor of 2.

Space complexity

The space complexity is O(1), which means it uses constant space. Since it does not require additional space, it is ideal for situations where memory space is limited.

Conclusion

Fibonacci search is an impactful and efficient search algorithm known for its exceptional performance, especially with large datasets. This algorithm requires no additional space, which positions it as a perfect fit for situations where memory space might be constrained. Its unique capability to work well with dynamically changing datasets, not requiring access to the entire dataset simultaneously, further highlights its robustness. However, it's worth noting that for a successful Fibonacci search, the array needs to be sorted first, which implies an investment of time and resources. Also, it may not be ideal for small arrays and is generally more complex to comprehend and implement when compared to other search algorithms such as linear search and binary search.

References

  • Algoritmi e programmazione in C di Francesco Oliveri, Aracne editrice (Italian book)

Top comments (19)

Collapse
 
kalkwst profile image
Kostas Kalafatis

Hey, this article seems like it may have been generated with the assistance of ChatGPT or some other AI tool. In fact, it marks over 72% on detectors.

We allow our community members to use AI assistance when writing articles as long as they abide by our guidelines. Could you review the guidelines and edit your post to add a disclaimer?

Collapse
 
fabriziobagala profile image
Fabrizio Bagalà

Hi, what tool did you use to make such a statement?

I would like to emphasize that none of my articles are written by AI. For transparency, I will now add the sources I learn from. Also, again for fairness, I use English grammar and spelling correction tools (such as LanguageTool, DeepL) because I am not a native speaker.

FYI the text produced by AI must always be reviewed and checked for errors. However, in the past, I have done pair programming with AI by suggesting my own corrections and I would not want this to impact my articles.

Collapse
 
kalkwst profile image
Kostas Kalafatis

Hey, I just wanted to bring something to your attention regarding your recent post. I'm not accusing you of plagiarizing content from AI, but I noticed that the detector (zerogpt.com/) actually marked your post as AI generated. I've read a lot of your articles before, since you tend to write under tags i moderate, and have tested them, so I know for a fact that you don't generally use AI tools to generate your posts. However, this post in particular seemed to be flagged by the tool for some reason. I ran some tests on the text of this specific post and found that it also marks as AI generated.

In fact, I've seen quite a lot of posts appearing on the platform that are marked as AI generated, so I think it's important that we do our due diligence and notify authors when their content is flagged as such. I just wanted to bring this to your attention in case you weren't aware, and also note that tools like Grammarly and Quillbot can sometimes cause detectors to mistakenly flag posts as AI generated. I use them too, since I am not a native speaker either. Thanks for your attention to this matter!

Thread Thread
 
fabriziobagala profile image
Fabrizio Bagalà

Hi again, thank you for bringing this issue to my attention. I will try to explain the same concept using different words, include references and see if this problem is solved. Unfortunately for tools like LanguageTool I cannot do much.

Thread Thread
 
kalkwst profile image
Kostas Kalafatis

It's not your content to be honest, from what I gather it's more about the formatting of the sentences, and how a text is structured. If you are using ChatGPT or Bard, you will notice that these tools tend to answer in a specific pattern, for example, they use bullet points. I would suggest that you would just change how you structure your post, and try to avoid bullet points.

I am not sure how the detectors work, since most of them are closed sourced, so I can't take a look under the hood. Don't change your posts now, just try to run your text through a detector and see where it lands, and maybe do some restructuring in the future. At least, this is what I do.

In any case, keep up the good work. I really enjoy your posts.

Thread Thread
 
fabriziobagala profile image
Fabrizio Bagalà

Thank you very much! I will follow your advice 😉

Thread Thread
 
webduvet profile image
webduvet

sorry I can't reply to the previous post. but I find it unacceptable to ask OP to change the text formatting just for not to get flagged by some AI detector.

Thread Thread
 
kalkwst profile image
Kostas Kalafatis

From a moderator's perspective, the purpose of flagging any post as AI-generated, at least in my view, is to reduce the presence of meaningless content on the platform. The goal is to ensure that the posts shared provide a substantial amount of useful information. When a post is flagged as AI-generated by an automated tool, the focus is primarily on the format rather than the value of the content itself. Even if someone manages to manipulate the formatting in a subtle way to deceive the tool, they still need to convince me with the actual substance of their content. It's not just about getting past the tool; the ultimate goal is to deliver valuable and meaningful contributions to the platform.

Imagine you're an author who diligently researches your material, studies the topic extensively, and invests hours into crafting your post. However, despite not using any tools like ChatGPT or Bard, you find that your post is flagged. It can be frustrating, right? In this scenario, how would you handle it? What approach would you take to address the situation while acknowledging the valid points raised?

Thread Thread
 
fabriziobagala profile image
Fabrizio Bagalà

I believe that both of you are right, and I will explain why.

On the author side, it doesn't make sense to change the formatting just to avoid being flagged by one or more AI detectors.

On the other hand, moderator side, the purpose is to reduce content with bad information and to avoid the frustration of those who take hours or days to write an article.

The solution then would be what? I think the solution is somewhere in between, which is mainly in common sense. Obviously this alone is not enough; adding references to understand where you have studied (because you must have studied somewhere) and, as far as possible, checking your text with an AI detector, such as ZeroGPT (suggested by @kalkwst), may be a good compromise.

Thread Thread
 
webduvet profile image
webduvet

As you said, as long the content meaningful and people find it interesting and helpful, honestly I don't care if it flagged by some AI tool or not. It insulting asking an original author to rephrase the content just because some bot is not working properly. Adjust the AI tool or use better one or not.

Thread Thread
 
webduvet profile image
webduvet

the premise shouldn't be AI generated content = bad content or bad information. There is nothing wrong in using AI tools to help to produce higher quality content free from mistakes and errors. Sure if somebody enters the prompt like "write an article on common programming mistakes" it qualifies for "garbage in garbage out". Once AI tools get so good that it will be possible to create in depth and accurate series of articles indistinguishable from work of a highly skilled professional and on any topic than blogging will be pretty much dead.

Thread Thread
 
kalkwst profile image
Kostas Kalafatis

However, it's crucial to make sure these posts are flagged as AI-generated. It's practically impossible for someone to judge whether a post is garbage or not until they've actually read it. Unfortunately, most authors don't bother to come forward and acknowledge that their article was AI-created, or at the very least, heavily influenced by AI output. As a result, the only way to label these posts as potentially unreliable is by flagging them as AI-generated in the comments. It's the only means we have to distinguish possible crap from genuine content in such cases.

Also, it's truly surprising to witness the lengths people would go to defend the authenticity of their posts as products of genuine human thinking, rather than mere outputs of AI algorithms. Astonishingly, some authors even resort to reporting comments that indicate their posts were AI-generated as spam or dismiss them as hurtful. These were articles that marked 90%+ across all of the detectors.

I get it. This approach isn't bulletproof, and there's a chance that legitimate authors might get flagged incorrectly, allowing some low-quality crap to slip by. But, honestly, it seems like the only solution we have at the moment. If you've got any other ideas or processes in mind, go ahead and suggest them. I'm all ears for alternative solutions.

Thread Thread
 
webduvet profile image
webduvet

perhaps transparency would help here. Add sticker by default to each article stating the AI buster tool(s) and version and the percentage it achieved and everyone can make up their own mind.

Thread Thread
 
kalkwst profile image
Kostas Kalafatis

You can add to the conversation here

Collapse
 
antidisestablishmentarianism profile image
Antidisestablishmentarianism

if (fibMMm1 == 1 and arr[offset + 1] == x)
Did you mean && instead of "and"?

Collapse
 
fabriziobagala profile image
Fabrizio Bagalà • Edited

I apologize for the mistake. Yes, I really meant the logical AND operator &&. Thank you for the heads up!

Collapse
 
fabriziobagala profile image
Fabrizio Bagalà

@kalkwst Following your advice I decided to put AI detector to the test. I made up a sentence about my favorite manga Dragon Ball 😄

"In the Dragon Ball saga, one of the most lovable characters is Majin Buu. He eats a sandwich and is friends with Mr. Satan."

The software Writer - AI Content Detector claims that my content is generated by an artificial intelligence.

Image description

Maybe I have become one with AI? 😂

Therefore this type of tools does not seem very reliable to me.
Tell me what you think.

Collapse
 
kalkwst profile image
Kostas Kalafatis • Edited

I believe that as chatbots become more and more human-like, the detectors will provide more and more false positives to be honest. It's like we are got in an arm's race between two networks (see GANs). Surely, there isn't a single source of truth here, you will get false positives no matter what. My work process on that is, I read the article and if I feel like it sounds a bit generated or feels too AI to me, I run the detectors. And if I see something that exceeds 72%-75% I try to contact the author. But even this is not foolproof. I have seen posts that feel like a log dump from ChatGPT and the detector said it's 0% generated, and I have seen your post that doesn't feel generated and it marks at 72%.

As I said it is more about sentence structure and not sentence content. I just use ZeroGPT because it actually marks what it believes that is AI-generated and either I try to change the sentence, or just go with it.

Collapse
 
fabriziobagala profile image
Fabrizio Bagalà

You are right when you state "as chatbots become more and more human-like, the detectors will provide more and more false positives." As mentioned above, I will take your advice: modify the sentence structure and use ZeroGPT to test it.