#include <iostream>
#include <string>
using namespace std;
/* abstract concretization */
int pow(int x, int n){
if (!n) return 1;
return (x * pow(x, n - 1));
}
int fib(int index){
if (index < 0) return -1;
if (!index) return 0;
if (index == 1) return 1;
return (fib(index - 2) + fib(index - 1));
}
//recursive helper function
void selectionSort(string &s, int start){
if (start == (s.size()-1)) return; //head:base case condition
//find the min's index
int min = s[start];
int minid = start;
for (int j = start; j < s.size(); ++j){
if (s[j] < min){
min = s[j];
minid = j;
}
} //body:the same operation
//swap
char temp;
temp = s[start];
s[start] = s[minid];
s[minid] = temp;
selectionSort(s, start + 1); //foot: recursion->reduce the scale
}
void selectionSort(string &s){
selectionSort(s, 0);
}
//recursive helper function
int binarySearch(const int array[], int begin, int end, int &key){
if (begin >= end) return -1; //base case condition 1
int mid = (begin + end) / 2;
if (key == array[mid]) return mid; //base case condition 2
else if(key < array[mid]) binarySearch(array, begin, mid - 1, key);
else binarySearch(array, mid + 1, end, key);
}
//return the entry index
int binarySearch(const int array[], int n, int key){
binarySearch(array, 0, n, key); //inner operation
}
//recursive helper function
bool isPalindrome(const char str[], int start, int end){
if (start >= end) return 0;
if (str[start] == str[end]) return 1;
else isPalindrome(str, start + 1, end - 1);
}
//determine if a string is Palindrome
bool isPalindrome(const char str[]){
isPalindrome(str, 0, strlen(str) - 1);
}
int line = 0;
/* Tower of Hanoi, each subproblem:
1. (n-1) disks : from -> aux with the help of to
2. the n-th disk : from -> to
3. (n-1) disks : aux -> to with the help of from
4. recursion until n equals to 1
*/
void hanoi(int n, char from[] = "A", char to[] = "B", char aux[] = "C"){
if (n == 1){
cout << ++line << " "<< from << " -> " << to << endl;
return;
}
hanoi(n - 1, from, aux, to);
cout << ++line << " " << from << " -> " << to << endl;
hanoi(n - 1, aux, from, to);
}
void reverse_print(const char str[])
{
if (str == NULL || *str == '\0')
return;
reverse_print(str + 1);
cout << *str;
}
//decode into the key
class Decode
{
public:
Decode(const char ch[])
{
count = 0;
memset(key, 0, 128);
Decode_helper(ch);
}
friend ostream& operator<<(ostream& o, Decode m);
private:
int count;
char key[128];
void Decode_helper(const char str[]);
};
//pratice, only consider alphabet
void Decode::Decode_helper(const char str[])
{
if (!(str[0])) return;
for (int i = 0; i < 26; ++i)
{
if (str[0] == 'a' + i || str[0] == 'A' + i)
{
key[count] = 'a' + i;
++count;
Decode::Decode_helper(str + 1);
return;
}
}
}
//print
ostream& operator<<(ostream& o, Decode m)
{
for (int i = 0; i < m.count; ++i)
o << m.key[i];
return o;
}
//New find? The function's position seems as if the stack?
int main(int argc, char const *argv[])
{
/*Code*/
return 0;
}
[Practice]Recursion (Continued)
最新推荐文章于 2021-03-05 09:17:59 发布