In file managers, file searching is used to find files with specific names. In IDEs, file searching is used to find program files with specific code text.
In this topic, we'll develop the first example in order to find a file named f211.txt. The folder structure is shown in the following screenshot:
This folder structure can be represented as a tree, as shown in the following diagram; the file that we're trying to find is shown with a green border:
Let's go ahead and look at how file searching will work to find this file:
- File searching starts in the current directory; it opens the first folder inside of that (d1) and opens the first folder in d1 (d11). Inside of d11, it compares all of the filenames.
- Since there's no more content inside of d11, the algorithm gets out of d11, goes inside of d1, and goes for the next folder, which is d12, comparing all of its files.
- Now, it moves outside of d12 and goes for the next folder inside of d1 (f11), and then the next folder (f12).
- Now, the search algorithm has covered all of the contents inside of the d1 folder. So, it gets out of d1 and goes for the next folder inside of the current directory, which is d2.
- Inside of d2, it opens the first folder (d21). Inside of d21, it compares all of the files, and we find the f211 file that we're looking for.
If you refer to the preceding folder structure, you will see that there's a pattern that is being repeated. When we reached f111, the algorithm had explored the leftmost part of the tree, upto its maximum depth. Once the maximum depth was reached, the algorithm backtracked to the previous level and went for the next subtree to the right. Again, in this case, the leftmost part of the subtree is explored, and, when we reach the maximum depth, the algorithm goes for the next subtree. This process is repeated until the file that we are searching for is found.
Now that we understand how the search algorithm functions logically, in the next topic, we will go through the main ingredients of searching, which are used for performing searching in this application.