0% found this document useful (0 votes)
15 views9 pages

DAA U-3

The document discusses brute force and exhaustive search algorithms, highlighting their applicability to various problems such as sorting, searching, and combinatorial problems like the Traveling Salesman Problem and the Knapsack Problem. It details specific algorithms like Selection Sort and Bubble Sort, explaining their processes and time complexities. Additionally, it covers the Linear Search algorithm, providing an implementation example and its operational steps.

Uploaded by

Ganesh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views9 pages

DAA U-3

The document discusses brute force and exhaustive search algorithms, highlighting their applicability to various problems such as sorting, searching, and combinatorial problems like the Traveling Salesman Problem and the Knapsack Problem. It details specific algorithms like Selection Sort and Bubble Sort, explaining their processes and time complexities. Additionally, it covers the Linear Search algorithm, providing an implementation example and its operational steps.

Uploaded by

Ganesh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 9

BRUTE FORCE

Brute force is a straight forward approach to solving a problem, usually directly based onthe
problem statement and definitions of the concepts involved.

Selection Sort, Bubble Sort, Sequential Search, String Matching, Depth-First Search and Breadth-First Search

Advantages:

1. Brute force is applicable to a very wide variety of problems.

2. It is very useful for solving small size in stances of a problem, even though it is inefficient.

3. The brute-force approach yields reasonable algorithms of at least some practical value with no
limitation on instance size for sorting, searching, and string matching.

Selection Sort
• First scan the entire given list to find its smallest element and exchange it with the first
element, putting the smallest element in its final position in the sorted list.
• Then scan the list, starting with the second element, to find the smallest among the last n −1
elements and exchange it with the second element, putting the second smallest element in its
final position in the sorted list.
• Generally, on the ith pass through the list, which we number from 0 to n − 2, the algorithm
searches for the smallest item among the last n −i elements and swaps it with Ai:

A0 ≤A1≤. .. ≤Ai–1|Ai, .. ., Amin,. .. ,An–1


In their final positions|the last n –i elements

• Aftern −1 passes, the list is sorted.

ALGORITHM Selection Sort(A[0..n−1])

//Sorts a given array by selection sort


//Input: An array A[0..n−1]of orderable elements
//Output: Array A[0..n−1] sorted in non decreasing order
for i ← 0 to n −2 do

min ← i

for j ←i +1 to n −1 do

if A[j]<A[min] min←j
swap A[i] and A[min]

|89 45 68 90 29 34 17
17 | 45 68 90 29 34 89
17 29 | 68 90 45 34 89
17 29 34 | 90 45 68 89
17 29 34 45 | 90 68 89
17 29 34 45 68 |90 89

www.ourcreativeinfo.in
17 29 34 45 68 89 |90

BubbleSort
The bubble sorting algorithm is to compare adjacent elements of the list and exchange them
if they are out of order. By doing it repeatedly, we end up “bubbling up” the largest element to the
last position on the list. The next pass bubbles up the second largest element, and so on, until
aftern−1passes the list is sorted.Passi(0≤i≤n−2)of bubble sort can be represented by the
?

following:A0,...,Aj⫘ Aj+1,...,An−i−1|An−i≤...≤An−1
ALGORITHMBubbleSort(A[0..n−1])

//Sortsa given array by bubble sort


//Input:AnarrayA[0..n−1]of orderable elements
//Output:ArrayA[0..n−1] sorted in nondecreasing order
fori ← 0 to n −2 do

forj ← 0 to n −2 −i do

ifA[j+1]<A[j]swapA[j]andA[j+1]

The action of the algorithm on the list 89,45, 68,90, 29,34,17 is example.

The number of key comparisons for the bubble-sort version given above is the same for all
arraysof size n; it is obtained by a sum that is almost identical to the sum for selection sort:
n−2 n−2−i n−2 n−2 (n −1)n

𝐶(𝑛)=∑ ∑1=∑[(n−2−i)−0+1]=∑(n−1−i)=
2
i=0 j=i+1 i=0 i=0
EXHAUSTIVE SEARCH
For discrete problems in which no efficient solution method is known,it might be necessary
to test each possibility sequentially in order to determine if it is the solution. Such exhaustive
examination of all possibilities is known as exhaustive search, complete search or direct search.

Exhaustive search is simply a brute force approach to combinatorial problems


(Minimization or maximization of optimization problems and constraint satisfaction problems).

Reason to choose brute-force / exhaustive search approach as an important algorithm


design strategy
1. First, unlike some of the other strategies, brute force is applicable to a very wide
variety of problems. In fact,it seems to be the only general approach for which it is
more difficult to point out problems it cannot tackle.
2. Second, for some important problems, e.g. sorting ,searching, matrix multiplication,
string matching the brute-force approach yields reasonable algorithms of at least
some practical value with no limitation on instance size.
3. Third, the expense of designing a more efficient algorithm may be unjustifiable if
only a few instances of a problem need to be solved and a brute-force algorithm can
solve those instances with acceptable speed.
4. Fourth, even if too inefficient in general, a brute-force algorithm can still be useful
for solving small-size instances of a problem.
Exhaustive Search is applied to the important problems like
• Traveling Salesman Problem
• Knapsack Problem

TRAVELING SALES MAN PROBLEM


The traveling salesman problem (TSP) is one of the combinatorial problems. The problem
asks to find the shortest tour through a given set of n cities that visits each city exactly once before
returning to the city where it started.

The problem can be conveniently modeled by a weighted graph, with the graph’s vertices
representing the cities and the edge weights specifying the distances. Then the problem can be
stated as the problem of finding the shortest Hamiltonian circuit of the graph. (A Hamiltonian
circuit is defined as a cycle that passes through all the vertices of the graph exactly once).
AHamiltoniancircuitcanalsobedefinedasasequenceofn+1adjacentvertices vi0, vi1, . . . , vin−1,
vi0, where the first vertex of the sequence is the same as the last one and all the other n − 1 vertices
are distinct. All circuits start and end at one particular vertex. Figure 2.4 presents a small instance
of the problem and its solution by this method.

www.ourcreativeinfo.in
Tour Length
a--->b--->c --->d--->a I=2 +8+1 +7 =18
a--->b--->d--->c--->a I= 2 + 3 + 1 + 5 = 11 optimal

a--->c--->b--->d--->a I=5 +8+3 +7 =23


a--->c--->d--->b--->a I= 5 + 1 + 3 + 2 = 11 optimal

a--->d--->b--->c--->a I=7 +3+8 +5 =23


a--->d--->c --->b--->a I=7 +1+8 +2 =18
FIGURE2.4 Solution to a small instance of the traveling salesman problem by exhaustive search.

Time efficiency
• We can get all the to by generating all the permutations of n−1intermediate cities
From a particular city..i.e.(n-1)!
• Consider two intermediate vertices,say,band c,and then only permutations in which b
Precedes c.(This trick implicitly defines tour’s direction.)
• An inspection of Figure 2.4reveals three pairs of tours that differ only by their direction.
Hence, we could cut the number of vertex permutations by half because cycle total
lengths in both directions are same.
• The total number of permutations needed is still 1(n − 1)!, which makes the exhaustive-
2
search approach impractical for large n. It is useful for very small values of n.

KNAPSACKPROBLEM
Given n items of known weights w1, w2, . .. , wnand values v1, v2, . . . , vnand a knapsack of
capacity W, find the most valuable subset of the items that fit into the knapsack.

Real time examples:


• A Thifwho wants to steal the most valuable loot that fits into his knapsack,
• A transport plane that has to deliver the most valuable set of items to are more location
Without exceeding the plane’s capacity.

The exhaustive-search approach to this problem leads to generating all the subsets of the set
of n items given,computing the total weigh to each subset inorder to identify feasible subsets(i.e.,
the ones with the total weight not exceeding the knapsack capacity), and finding a subset of the
largest value among them.

www.ourcreativeinfo.in
FIGURE2.5Instance of the knapsack problem.

Subset Total weight Total value


Φ 0 $0
{1} 7 $42
{2} 3 $12
{3} 4 $40
{4} 5 $25
{1, 2} 10 $54
{1, 3} 11 Not feasible
{1, 4} 12 Not feasible
{2, 3} 7 $52
{2, 4} 8 $37
{3, 4} 9 $65(Maximum-Optimum)
{1, 2, 3} 14 Not feasible
{1, 2, 4} 15 Not feasible
{1, 3, 4} 16 Not feasible
{ 2, 3, 4} 12 Not feasible
{1, 2, 3, 4} 19 Not feasible
FIGURE2. 6 knapsack problem’s solution by exhaustive search. The information about the
optimal
Selection is in bold.
Time efficiency: As given in the example, the solution to the instance of Figure 2.5 is given in
Figure 2.6. Since the number of subsets of an n-element set is 2n, the exhaustive search leads
to a Ω(2n) algorithm, no matter how efficiently individual subsets are generated.

www.ourcreativeinfo.in
Note:Exhaustive search of both the traveling salesman and knapsack problems leads to extremely
inefficient algorithms on every input. In fact, these two problems are the best-known examples of NP-
hard problems. No polynomial-time algorithm is known for any NP-hard problem. Moreover, most
computer scientists believe that such algorithms do not exist. some sophisticated approaches like
backtracking and branch-and-bound enable us to solve some instances but not all instances of these in
less than exponential time. Alternatively, we can use one of many approximation algorithms.

Linear Search Algorithm(Sequential Search)

What is Search?

Search is a process of finding a value in a list of values. In other words, searching is the
processof locating given value position in a list of values.

Linear Search Algorithm (Sequential Search Algorithm)

• Linear search algorithm finds given element in a list of elements with O(n)
timecomplexity where n is total number of elements in the list.
• This search process starts comparing of search element with the first element in the list.
• If both are matching then results with element found otherwise search element
iscompared with next element in the list.
• If both are matched, then the result is "element found". Otherwise, repeat the same
with the next element in the list until search element is compared with last element in
the list.
• if that last element also doesn't match, then the result is "Element not found in the
list".That means, the search element is compared with element by element in the list.

Linear search is implemented using following steps...

Step 1: Read the search element from the user

Step 2: Compare, the search element with the first element in the list.

Step 3: If both are matching, then display "Given element found!!!" and terminate the function

Step 4: If both are not matching, then compare search element with the next element in the list.

Step 5: Repeat steps 3 and 4 until the search element is compared with the last element in the

www.ourcreativeinfo.in
list.

Step 6: If the last element in the list is also doesn't match, then display "Element not found!!!"and

terminate the function.

www.ourcreativeinfo.in
1. #include <stdio.h>
2.
3. int linearSearch(int arr[], int n, int target) {
4. int i;
5. for (i = 0; i< n; i++) {
6. if (arr[i] == target) {
7. return i; // Element found at index i8.
}
9. }
10. return -1; // Element not found
11. }
12.
13. int main() {
14. int arr[] = {10, 2, 8, 5, 17};
15. int n = sizeof(arr) / sizeof(arr[0]);
16. int target = 8;
17. int result = linearSearch(arr, n, target);
18. if (result == -1) {
19. printf("Element not found in the array.\n");
20. } else {
21. printf("Element found at index: %d\n", result);
22. }
23. return 0;
24. }

Assuming that the target element is 8, let's use the example array [10, 2, 8, 5, 17]. Running the code
yields the following result:

Element found at index: 2

The element '8' was found in this instance by the linear search technique at index 2 of the array.

Let's dissect the implementation process in detail:

1. To use the printf function, we include the h library.


2. The array arr[], the array's size n, and the element to be searched are the three arguments
provided to the linear Search function.
3. We create the integer variable i and use a for loop to iterate through the array.
4. We compare each element of the array with the target element inside the loop.
5. If a match is discovered, we return the element's location's index.

www.ourcreativeinfo.in
6. We return -1 to denote that the element was not found if, after searching the full array, no
matches were discovered.
7. We declare an array called arr[] with a few random members in the main function.
8. By dividing the array's overall size by the size of a single member, we may get the array's n-
dimensional size.
9. The target element we wish to look for is specified (in this example, 8).
10. The array, size, and target are passed as arguments when we use the linear Search function,
and we store the result in the result variable.
11. Finally, we evaluate the value of the outcome. We print a message explaining that the
element was not found if it is -1. If not, we display the index at which the element was
located.

www.ourcreatuveinfo.in

www.ourcreativeinfo.in

You might also like