The table that follows contains the pseudo code for a typical divide and conquer
algorithm.
find_solution(a_problem) {
if (size.of.a_problem <= minimum_size)
return results;
else {
split_problem a_problem;
find_solution (a_problem1);
find_solution (a_problem2);
...
find_solution (a_problemn);
glue_solutions_together;
}
}
|
The following table shows a generic tail recursion algorithm.
find_solution(a_problem) {
if (size.of.a_problem <= minimum_size)
return solution;
else {
split_problem a_problem;
select_subproblem a_problemi;
find_solution((a_problemi);
}
}
|
find_solution(a_problem) {
while (size.of.a_problem > minimum_size) {
split_problem;
select ith subproblem
a_problem = a_problemi
}
return solution;
}
|
| Even Number | [0] | [1] | [2] | [3] | [4] | [5] | [6] | [7] | [8] | [9] | |
| 10 | 20 | 30 | 40 | 50 | 60 | 70 | 80 | 90 | 100 | ||
| Odd Number | [0] | [1] | [2] | [3] | [4] | [5] | [6] | [7] | [8] | [9] | [10] |
| 5 | 10 | 20 | 30 | 40 | 50 | 60 | 70 | 80 | 90 | 100 |
| Even | Odd |
|---|---|
[4]
/ \
[1] [7]
/ \ / \
[0] [2][5] [8]
\ \ \
[3][6] [9]
|
[5]
/ \
[2] [8]
/ \ / \
[1] [3][6] [9]
/ \ \ \
[0] [4][7] [10]
|
#include <stdio.h> #include <stdlib.h> #define MAX_SIZE 101 #define NOT_FOUND -100 #define LESS -1 #define SAME 0 #define GREATER 1 #define COMPARE(x, y) ((x) < (y) ? LESS : (x) == (y) ? SAME : GREATER) void create_array(int [], int *); void print_array (int [], int); void selection_sort(int [], int); int binary_search(int [], int, int); void swap(int *, int *); |
The binary search returns the array position of the number if it is in the
array; otherwise it returns NOT_FOUND.
int main()
{
int size,searchnum,position;
int numbers[MAX_SIZE];
create_array(numbers, &size);
selection_sort(numbers,size);
print_array(numbers, size);
printf("Enter the number to find: (-1 to quit): ");
scanf("%d",&searchnum);
while ( searchnum > -1) {
if ((position = binary_search(numbers,searchnum,size)) == NOT_FOUND)
printf("The number is not in the array \n\n");
else
printf("The number was found in the %d position\n\n",position);
printf("Enter the number to find (-1 to quit): ");
scanf("%d",&searchnum);
}
}
|
int binary_search(int numbers[], int searchnum, int size)
{
int lower_bound = 0, upper_bound = size-1, middle_position;
while (lower_bound <= upper_bound) {
middle_position = (lower_bound+upper_bound)/2;
printf("Lower bound %d Middle Position %d", lower_bound, middle_position);
printf(" Upper bound %d\n",upper_bound);
switch (COMPARE(numbers[middle_position], searchnum)) {
case LESS : lower_bound = middle_position + 1;
break;
case SAME : return middle_position;
case GREATER : upper_bound = middle_position - 1;
}
}
return NOT_FOUND;
}
|