DAA U-3
DAA U-3
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:
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:
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])
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.
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
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.
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.
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.
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 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.
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
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:
The element '8' was found in this instance by the linear search technique at index 2 of the array.
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