0% found this document useful (0 votes)
17 views29 pages

Dsa Lab 3 Searching

Uploaded by

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

Dsa Lab 3 Searching

Uploaded by

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

Data Structure and

Algorithms
LE SUMAYA AMIN
Link-List

 Write a code for following output:

Output
Searching

 Searching is the process of finding a particular data in the collection.


 Types of searching :
1. Linear
2. Binary
Linear Search

 Description: A simple search method that sequentially checks each


element in the list until the desired element is found or the list ends.]

 Best for: Unordered or small datasets.

 Time Complexity: O(n), where n is the number of elements.


Binary Search

 Description: A more efficient search technique for sorted datasets. It


repeatedly divides the search interval in half and checks whether the
middle element matches the target value. If not, it eliminates half of
the search space.

 Best for: Sorted datasets.

 Time Complexity: O(log n).


Low, Mid & High
Linear Search Pseudocode

LINEAR(DATA,N, ITEM,LOC)
Set DATA[N+1] = ITEM
Set LOC = 1
Repeat while DATA[LOC] !=ITEM
Set LOC = LOC +1
If LOC = N+1, then Set LOC =0
Exit.
Pseudocode (Linear Search Algo)

 Set DATA[N+1] = ITEM:


This line places the ITEM (the target element) at the end of the array DATA as a sentinel value. This sentinel
ensures the loop will terminate even if the ITEM is not found in the first N elements.

 Set LOC = 1:
LOC is initialized to 1, indicating the starting position of the search. It represents the index or location of the
current element being compared.

 Repeat while DATA[LOC] != ITEM:


The loop will keep checking each element in DATA until it finds the ITEM or reaches the sentinel value at
position N+1.

 Set LOC = LOC + 1:


Increment LOC by 1 after each comparison. This moves the search to the next element in the array.

 If LOC = N+1, then Set LOC = 0:


If LOC reaches N+1, which is the location of the sentinel, it means the ITEM was not found within the first N
elements. So, LOC is set to 0, indicating the ITEM is not present in the original list.

 Exit:
The search terminates either when the ITEM is found (when DATA[LOC] == ITEM) or when LOC reaches N+1
(indicating ITEM was not found and the search ends).
Binary search Pseudocode

Set BEG=LB,
END=UB,
and MID= INT((BEG+END)/2)
Repeat Steps 3 and 4 while BEG<=END and DATA[MID]!=ITEM
if ITEM<DATA[MID] then
set END=MID – 1
else
set BEG = MID +1
Set MID = = INT((BEG+END)/2)
if DATA[MID]=ITEM, then
set LOC = MID
else
set LOC = NULL
Exit.
 Set BEG = LB, END = UB, and MID = INT((BEG + END) / 2):
BEG is initialized to LB (lower bound), and END is set to UB (upper bound),
which represent the current search range within the array.MID is calculated
as the middle index of the array using the formula: (BEG + END) / 2. The
function INT takes the integer part of the division to get a valid index.

 Repeat Steps 3 and 4 while BEG <= END and DATA[MID] != ITEM:
The loop continues as long as the search range (BEG ≤ END) is valid, and
the item at the middle index MID is not equal to the target ITEM.

 if ITEM < DATA[MID] then set END = MID – 1:


If the target ITEM is less than the middle element DATA[MID], then the
search continues in the left half of the current range by setting END to MID -
1.

 else set BEG = MID + 1:


If the target ITEM is greater than the middle element DATA[MID], the search
continues in the right half by setting BEG to MID + 1.
 Set MID = INT((BEG + END) / 2):
After adjusting the search bounds (BEG or END), the middle index MID is
recalculated to focus on the new search range.

 if DATA[MID] = ITEM, then set LOC = MID:


If the target ITEM is found at the middle index MID, the location (LOC) is
set to MID and the search is successful.

 else set LOC = NULL:


If the loop exits because BEG exceeds END without finding the ITEM, LOC
is set to NULL, indicating that the item is not present in the array.

 Exit:
The algorithm terminates either when the ITEM is found or when the
search range is exhausted, meaning the ITEM is not in the array.
Lab Task

Exercise 1:
Create function for each algorithm using Array:
Linear search
Binary search
Input list of numbers: 6 13 14 25 33 43 51 53 64 72 84 93 95 96 97

Exercise 2:
Write a program to search an element linearly from the entered numbers. Also, indicate its
position in case the element is found or unavailability.

Exercise :
Write a program to demonstrate binary search. Use character array and store 10 names. This
program prompts the user to enter ten names. They are stored in ascending order the name[15]
[10] the fn[15] is used to store the name which we want to search.
SORTING

 Sorting is the process of arranging values in any particular order. The


order can be ascending or descending.
 Types of sorting:

1. selection
2. insertion
3. bubble
4. merge sort
Selection Sort

 Find the minimum value in the list


 Swap it with the value in the first position
 Repeat the steps above for remainder of the list (starting at the
second position)
Pseudocode
SELECTION_SORT(DATA, N)
1. For i = 0 to N - 1:
a. Set min_index = i
b. For j = i + 1 to N - 1:
i. If DATA[j] < DATA[min_index], then:
- Set min_index = j
c. If min_index != i, then:
- Swap DATA[i] and DATA[min_index]
2. End For
 Step 1: Loop through each element of the array (from 0 to N-1).

 Step 1a: Assume the current element at index i is the smallest


element (set min_index).

 Step 1b: Check the rest of the array (starting from i+1) to find if any
element is smaller than the current minimum.

 Step 1c: If a smaller element is found, swap it with the element at i.

 This ensures that the smallest element is placed in position i at the


end of each iteration.
Insertion Sort

 This algorithm takes one value at a time and builds up another sorted
list of values. It helps if you can imagine what you do when you play a
game of cards: you pick a card and insert it to an already sorted list
of cards.
def insertion_sort(A):
# Iterate over each element starting from the second element
for i in range(1, len(A)):
value = A[i]
j=i-1
# Repeat shifting elements until the correct position for 'value' is found
while j >= 0 and A[j] > value:
A[j + 1] = A[j]
j -= 1
# Place 'value' into its correct position
A[j + 1] = value

# Example usage
array = [12, 11, 13, 5, 6]
insertion_sort(array)
print("Sorted array:", array)
Bubble Sort

 This algorithm looks at pairs of entries in the array and swaps their
order if needed. After the first step of the algorithm the maximal
value will "bubble" up the list and will occupy the last entry. After the
second iteration, the second largest value will "bubble" up the list and
will occupy the next to last entry, and so on.
procedure BubbleSort(arr, n)
for i from n-1 down to 1 do // Outer loop runs from last element
to first
for j from 0 to i-1 do // Inner loop runs from the first element
to 'i-1'
if arr[j] > arr[j+1] then // Compare adjacent elements
swap(arr[j], arr[j+1]) // Swap if the left element is greater
than the right
end for
end procedure
Merge Sort

Merge Sort:This recursive algorithm belongs to the very important divide-and-conquer


paradigm. It consists of the following steps:
 Divide-the elements to be sorted into two groups of equal (or almost equal) size.
 Conquer - Sort each of these smaller groups of elements (by recursive calls).

Merge - Combine the two sorted groups into one large sorted list
funcmergesort( var a as array )
if ( n == 1 ) return a
var l1 as array = a[0] ... a[n/2]
var l2 as array = a[n/2+1] ... a[n]
l1 = mergesort( l1 )
l2 = mergesort( l2 )
return merge( l1, l2 )
end func
func merge( var a as array, var b as array )
var c as array
while ( a and b have elements )
if ( a[0] > b[0] )
add b[0] to the end of c
remove b[0] from b
else
add a[0] to the end of c
remove a[0] from a
while ( a has elements )
add a[0] to the end of c
remove a[0] from a
while ( b has elements )
add b[0] to the end of c
remove b[0] from b
return c
end func
Code Breakdown
 if (n == 1) return a
If the array has only one element (n == 1), it is already sorted, so the
function returns the array as it is

 var l1 as array = a[0] ... a[n/2]


var l2 as array = a[n/2+1] ... a[n]
The array a is divided into two halves:
l1 is the left half, containing the first n/2 elements of a.
l2 is the right half, containing the remaining elements from a[n/2+1] to
a[n].
 l1 = mergesort(l1)
l2 = mergesort(l2)
The mergesort function is called recursively on both the left half (l1) and
the right half (l2), sorting them individually.
 return merge(l1, l2)
After both halves are sorted, the merge function is called to merge the two sorted
arrays l1 and l2 into one sorted array, which is then returned.
merge function:
The merge function takes two sorted arrays (a and b) as input and merges them
into a single sorted array (c).

 while (a and b have elements)


if (a[0] > b[0])
add b[0] to the end of c
remove b[0] from b
else
add a[0] to the end of c
remove a[0] from a
As long as both a and b have elements, it compares the first elements of each
(a[0] and b[0]).
If the first element of a is larger (a[0] > b[0]), it adds the first element of b to the
merged array c and removes it from b.
Otherwise, it adds the first element of a to c and removes it from a.
Adding Remaining Elements:
After one of the arrays (a or b) is empty, the remaining elements from
the other array are added to c.

 while (a has elements)


add a[0] to the end of c
remove a[0] from a
while (b has elements)
add b[0] to the end of c
remove b[0] from b
These loops add the remaining elements from a or b to c once the other
array is fully merged
 return c
Lab Task

Exercise 1:
Write a program to sort a given array by using the insertion sort.

Exercise 2:
Write a program to sort a given array by using the selection sort.

Exercise 3:
Write a program to sort a given array by using the bubble sort.

Exercise 4 :
Write a program to sort a given array by using the merge sort.

You might also like