-
April 1st, 2006, 11:00 PM
#1
Linear search using recursive function
Hello,
I'm new here and am seeking some help with an assignment. I understand that a recursive function calls itself. However, I've been working on this assignment for some time and can't get it to work. Can someone help by stating what part of my code is wrong and explain why? I'm confused because I don't understand how a recursive function would handle an array. I've searched and only found the Fibonacci Series.
The assignement is to use a recursive function called linearSearch to perform linear search of the array. The function should receive an interger array and the size of the array as arguments. If the search key is found, return the array subscript; otherwise, return -1.
Thank you very much for any help.
Code:
#include <iostream>
#include <conio.h>
using namespace std;
int linearSearch( int [], int );
int main()
{
const int arraySize = 100;
int a[arraySize];
int element;
for( int i = 0; i < arraySize; i++)
{
a[i] = 2 * i;
}
element = linearSearch( a, arraySize );
if( element != -1 )
cout << "Found value in element " << element << endl;
else
cout << "Value not found." << endl;
getch();
return 0;
}
int linearSearch( int array[], int counter )
{
if( linearSearch( array, counter - 1 ) != 10 )
return counter;
else
return -1;
}
-
April 1st, 2006, 11:41 PM
#2
Re: Linear search using recursive function
Code:
#include <iostream>
#include <conio.h>
using namespace std;
/*
Linear Search
Description:
Searches array recursively for value 10.*/
int linearSearch(int array[],int counter) {
--counter;
if (counter < 0)
return -1; // value not found
if (array[counter] == 10)
return (counter+1); // found value at returned position (index starting with 1)
else
return linearSearch(array,counter); // continue search
}
/*
Conventional entrypoint of the application
Description:
Allocates an array of 100 elements with values as even numbers starting with 0 and then calls the linearSearch function.*/
int main() {
const int arraySize = 100;
int a[arraySize];
register int i = arraySize;
while (i) { --i;
a[i] = 2 * i;
}
int element = linearSearch(a,arraySize);
if (element < 0) { // element not found
cout << "Value not found." << endl;
}
else { // element found
cout << "Found value in element # " << element << endl;
}
getch();
return 0;
}
Best regards,
-
April 2nd, 2006, 12:18 AM
#3
Re: Linear search using recursive function
Thank you for your help. This will help me a lot with the other recursion assignments. Thanks again.
-
April 20th, 2006, 01:42 AM
#4
-
April 20th, 2006, 02:10 AM
#5
Re: Linear search using recursive function
I hope, you are aware that you are searching backwards. The result will be (maybe) unexpected if your array contains two 10s.
-
February 17th, 2014, 05:00 AM
#6
Re: Linear search using recursive function
Originally Posted by treuss
I hope, you are aware that you are searching backwards. The result will be (maybe) unexpected if your array contains two 10s.
Another example that can be helpful
http://fahad-cprogramming.blogspot.com/2014/02/linear-search-program-in-c-using.html
-
February 18th, 2014, 02:19 AM
#7
Re: Linear search using recursive function
Also I suggest that you do a bit more research on recursion. The more you study about it, the more you understand how easy it is ( equivalent to writing a simple formula ). The reason I'm saying this because it is a vastly used technique and considered good software engineering if you plan to become one. Moreover it is more understandable by another user who is to edit your code and given an edge over looping ( as long as your stack doesn't blow up ). Indeed your professor chose a poor example to illustrate the concept but what can he do. He can't make you write 1000 lines of code and just say to his students that the only point was to show that recursion is a good technique. It may very well be the last thing he says...
-
February 18th, 2014, 04:41 AM
#8
Re: Linear search using recursive function
Originally Posted by dcjr84
A lot of overhead is created here because function calls have to be allocated on the stack, and for something so trivial as a linear search a lot of resources will be wasted by using recursion.
Are you sure?
Tail recursion is well studied and a staple of functional programming. Most C++ compilers will be able to replace tail recursion with an iterative equivalent so there will be no runtime penalty.
-
February 18th, 2014, 07:54 AM
#9
Re: Linear search using recursive function
Originally Posted by razzle
Are you sure?
Tail recursion is well studied and a staple of functional programming. Most C++ compilers will be able to replace tail recursion with an iterative equivalent so there will be no runtime penalty.
YEs, I'm sure.
it may be well studied, but it's still not a good idea to rely on compiler features to obtain a certain effect. Expecting a compiler to turn a recursive call into an iterative process is quite a stretch to rely on.
This one in particular I would consider "a bad example of recursion", yes, you can enforce any iterative process into a recursive one, but that doesn't mean it's logical or straightforward to do so. A linear search is at heart an iterative process, so it makes little sense to try and turn it into a recursive solution. I.m.o. it will cause more confusion to the students than it actually solves because of the inate "weird way of thinking". In that light, I would say this is a bad example of using recursion.
Fibonacci numbers are a good example of where it "makes sense", but where at the same time there is a strong motivation against using recursion because of excessive runtime for the higher numbers (mainly caused by the double recursive call). So it's a good example of where recursion might be intuitive, yet inappropriate because recursion comes at a cost.
Other good examples would be directory searches, tree/menu traversal, quicksort, radix sort, expression parsing (ok, quite advanced this one), several "AI" techniques such as pathfinding, fill algorithms, ...
-
February 18th, 2014, 08:00 AM
#10
Re: Linear search using recursive function
Originally Posted by parikshit6321
Indeed your professor chose a poor example to illustrate the concept but what can he do. He can't make you write 1000 lines of code and just say to his students that the only point was to show that recursion is a good technique.
Seeing this quite a lot tbh. Poor examples because of lazyness of the person writing the exercices.
If recursion isn't intuitive, then i.m.o. it's a bad idea to try and use it as an example.
There are plenty of simple exercies where you can intuitively explain why recursion would be a good fit and not require 1000 lines of code to write to see it happen.
replacing a for-loop by a recursive call is imo a horribad example.
-
February 18th, 2014, 08:19 AM
#11
Re: Linear search using recursive function
Personally, I like the towers of Hanoi as an example. The whole program is only about a dozen lines.
All advice is offered in good faith only. All my code is tested (unless stated explicitly otherwise) with the latest version of Microsoft Visual Studio (using the supported features of the latest standard) and is offered as examples only - not as production quality. I cannot offer advice regarding any other c/c++ compiler/IDE or incompatibilities with VS. You are ultimately responsible for the effects of your programs and the integrity of the machines they run on. Anything I post, code snippets, advice, etc is licensed as Public Domain https://creativecommons.org/publicdomain/zero/1.0/ and can be used without reference or acknowledgement. Also note that I only provide advice and guidance via the forums - and not via private messages!
C++23 Compiler: Microsoft VS2022 (17.6.5)
-
February 18th, 2014, 09:17 AM
#12
Re: Linear search using recursive function
Originally Posted by OReubens
If recursion isn't intuitive, then i.m.o. it's a bad idea to try and use it as an example.
... unless it is a functional programming course where immutability is a requirement and loop-like imperative solutions are not possible even in principle. That said, I too wonder what's the point of introducing functional programming concepts in a basic C or C++ course ...
Moreover, I'm not so sure that such optimization actually always takes place, at least so reliably to advocate its use by non experts. For example, how does tail recursion works with varying calling conventions ? how does it interact with the more and more common use of RAII making so easy to write "apparent" tail recursive functions ? what about exceptions ? ...
-
February 18th, 2014, 09:27 AM
#13
Re: Linear search using recursive function
Originally Posted by OReubens
YEs, I'm sure.
No you're opinionated and/or have never used a functional language.
Your "advice" as to when recursion is appropriate is very arbitrary to say the least. For example visiting the first 10 nodes of a list and generating the first 10 Fibonacci numbers both represent linear sequences that can be formulated both iteratively and recursively. Still the former would be a bad example of recursion while the latter would make sense. Why really?
My reply to dcjr84 (although he isn't likely to read it ten years after ) was regarding tail recursion specifically. It's a special case and both GCC and VC++ replace it with iteration (in release mode optimized for speed). Yes you can rely on that.
So if a sequence has a natural tail recursive definition I would consider using it. And if you're into template metaprogramming you don't have much of a choise because recursion is your only option.
Last edited by razzle; February 19th, 2014 at 01:15 AM.
-
February 19th, 2014, 01:09 AM
#14
Re: Linear search using recursive function
Originally Posted by superbonzo
That said, I too wonder what's the point of introducing functional programming concepts in a basic C or C++ course ...
I was surprised that C++ was used as model language in what seems like a basic programming course. But then I realized this thread is almost 10 years old and at that time the marginalization of C++ in education wasn't yet as pronounced as today.
Most introductory C++ courses held at colleges and universities are for advanced students and since C++ is a multiparadigmic language I see no reason why predominantly functional concepts like say recursion and lambda expressions should be left out.
Last edited by razzle; February 19th, 2014 at 05:31 AM.
-
February 19th, 2014, 01:44 AM
#15
Re: Linear search using recursive function
Originally Posted by OReubens
replacing a for-loop by a recursive call is imo a horribad example.
You're absolutely right.
As we all know C++ is especially well suited for us old-timers with an ancient education who want to hang on to C style coding the last few years before retirement. A good example of the versatility of C++ is the while-loop, an adventurous alternative to the more secure for-loop. But of course it should only be used when absolutely necessary and with uttermost care. Or as we so succinctly express it at my shop: Go for for, use while in a while!
Functional programming. Object orientation. Template metaprogramming. Recursion. Lambda expressions. Smart pointers. Concurrency. Devirualization. Tail call removal. What bull is this? Have people gone raving mad!!!
Last edited by razzle; February 20th, 2014 at 03:57 AM.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|