0% found this document useful (0 votes)
21 views

DSA Arrays (1)

Uploaded by

duazahra9795
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)
21 views

DSA Arrays (1)

Uploaded by

duazahra9795
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/ 77

DATA STRUCTURE

AND ALGORITHMS -
ARRAYS
Dr. Muhammad Awais Sattar
Assistant Professor RSCI

1
ARRAYS/LISTS
 An array is a data structure used to store multiple
elements.
 Arrays are used by many algorithms.
 For example, An algorithm can be used to look through
an array to find the lowest value
 In Python, an array can be created like this:
my_array = [7, 12, 9, 4, 11]
ARRAYS/LISTS
 Arrays are indexed, meaning that each element in the
array has an index, a number that says where in the
array the element is located.
 Python use zero-based indexing for arrays, meaning that
the first element in an array can be accessed at index 0.

my_array = [7, 12, 9, 4, 11]


print( my_array[0] )
ALGORITHM: FIND THE LOWEST
VALUE IN AN ARRAY
 How it works:
• Go through the values in the array one by one.
• Check if the current value is the lowest so far, and if it is, store it.
• After looking at all the values, the stored value will be the lowest
of all values in the array.
ALGORITHM: FIND THE LOWEST
VALUE IN AN ARRAY
 Implementation
• Before implementing the algorithm using an actual programming
language, it is usually smart to first write the algorithm as a
step-by-step procedure.
• If you can write down the algorithm in something between
human language and programming language, the algorithm will
be easier to implement later because we avoid drowning in all
the details of the programming language syntax.
ALGORITHM: FIND THE LOWEST
VALUE IN AN ARRAY
 Implementation
1. Create a variable 'minVal' and set it equal to the first value of
the array.
2. Go through every element in the array.
3. If the current element has a lower value than 'minVal', update
'minVal' to this value.
4. After looking at all the elements in the array, the 'minVal'
variable now contains the lowest value.

OR
ALGORITHM: FIND THE LOWEST
VALUE IN AN ARRAY

Variable 'minVal' = array[0]


For each element in the array
If current element < minVal
minVal = current element
ALGORITHM: FIND THE LOWEST
VALUE IN AN ARRAY
 After we have written down the algorithm, it is much easier
to implement the algorithm in a specific programming
language:
my_array = [7, 12, 9, 4, 11]
minVal = my_array[0] # Step 1
for i in my_array: # Step 2
if i < minVal: # Step 3
minVal = i
print('Lowest value: ',minVal) # Step 4
ALGORITHM TIME COMPLEXITY
 When exploring algorithms, we often look at
how long time an algorithm takes to run
relative to the size of the data set.
 In the example above, the time the algorithm
needs to run is proportional, or linear, to the
size of the data set.
 This is because the algorithm must visit
every array element one time to find the
lowest value.
 The loop must run 5 times since there are 5
values in the array.
 If the array had 1000 values, the loop would
have to run 1000 times.
BUBBLE SORT
 Bubble Sort is an algorithm that sorts an array from the
lowest value to the highest value.
 The word 'Bubble' comes from how this algorithm
works, it makes the highest values 'bubble up’.
BUBBLE SORT
 How it works:
1. Go through the array, one value at a time.
2. For each value, compare the value with the next value.
3. If the value is higher than the next one, swap the values so that the
highest value comes last.
4. Go through the array as many times as there are values in the
BUBBLE SORT
Manual Run Through
 Step 1: We start with an unsorted array.
[7, 12, 9, 11, 3]
 Step 2: We look at the two first values. Does the lowest
value come first? Yes, so we don't need to swap them.
[7, 12, 9, 11, 3]
 Step 3: Take one step forward and look at values 12 and 9.
Does the lowest value come first? No.
[7, 12, 9, 11, 3]
BUBBLE SORT
 Step 4: So we need to swap them so that 9 comes first.
[7, 9, 12, 11, 3]
 Step 5: Taking one step forward, looking at 12 and 11.
[7, 9, 12, 11, 3]
 Step 6: We must swap so that 11 comes before 12.
[7, 9, 11, 12, 3]
BUBBLE SORT
 Step 7: Looking at 12 and 3, do we need to swap them?
Yes.
[7, 9, 11, 12, 3]
 Step 8: Swapping 12 and 3 so that 3 comes first.
[7, 9, 11, 3, 12]
 Can you see what happened to the highest value 12?
• It has bubbled up to the end of the array, where it belongs. But
the rest of the array remains unsorted.
BUBBLE SORT
 So the Bubble Sort algorithm must run through the array
again, and again, and again.
 Each time the next highest value bubbles up to its
correct position. The sorting continues until the lowest
value 3 is left at the start of the array.
 This means that we need to run through the array 4
times, to sort the array of 5 values.
BUBBLE SORT
Bubble Sort Implementation
1. An array with values to sort.
2. An inner loop that goes through the array and swaps
values if the first value is higher than the next value.
This loop must loop through one less value each time it
runs.
3. An outer loop that controls how many times the inner
loop must run. For an array with n values, this outer
loop must run n-1 times.
BUBBLE SORT
 Code:

my_array = [64, 34, 25, 12, 22, 11, 90, 5]


n = len(my_array)
for i in range(n-1):
for j in range(n-i-1):
if my_array[j] > my_array[j+1]:
my_array[j], my_array[j+1] = my_array[j+1],
my_array[j]
print("Sorted array:", my_array)
BUBBLE SORT
Bubble Sort Improvement:
 Imagine that the array is almost sorted already, with the
lowest numbers at the start, like this for example:
my_array = [7, 3, 9, 12, 11]
 In this case, the array will be sorted after the first run, but
the Bubble Sort algorithm will continue to run, without
swapping elements, and that is not necessary.
 If the algorithm goes through the array one time without
swapping any values, the array must be finished sorted, and
we can stop the algorithm, like this:
BUBBLE SORT
def bubble_sort_optimized(arr):
n = len(arr)
for i in range(n):
swapped = False
for j in range(0, n-i-1):
if arr[j] > arr[j+1]:
arr[j], arr[j+1] =
arr[j+1], arr[j]
swapped = True
# If no elements were swapped in
the inner loop, the list is sorted # Example usage:
arr = [5, 1, 4, 2, 8]
if not swapped: bubble_sort_optimized(arr)
break print("Optimized sorted array:", arr)
BUBBLE SORT
 Using Recursion
def bubble_sort_recursive(arr, n=None):
if n is None:
n = len(arr)
# Base case: if only one element, the
array is already sorted # Example usage:
if n == 1: arr = [3, 6, 1, 8, 4]
bubble_sort_recursive(arr)
return
print("Recursively sorted array:",
# One pass of bubble sort. After this arr)
pass, the largest element is at the end.
for i in range(n - 1):
if arr[i] > arr[i + 1]:
arr[i], arr[i + 1] = arr[i +
1], arr[i]
# Largest element is fixed, recur for
remaining array
bubble_sort_recursive(arr, n - 1)
BUBBLE SORT
 The Bubble Sort algorithm loops
through every value in the array,
comparing it to the value next to it.
So for an array of n values, there
must be n such comparisons in one
loop.
 And after one loop, the array is looped
through again and again n times.
 This means there are n⋅n comparisons
done in total, so the time complexity As you can see, the run time
for Bubble Sort is: increases really fast when the size of
the array is increased.
SELECTION SORT
 The Selection Sort algorithm finds the lowest value in an
array and moves it to the front of the array.
 The algorithm looks through the array again and again,
moving the next lowest values to the front, until the array is
sorted.
SELECTION SORT
How it works:
1.Go through the array to find the lowest value.
2.Move the lowest value to the front of the unsorted part
of the array.
3.Go through the array again as many times as there are
values in the array.
SELECTION SORT
Manual Run Through
 Step 1: We start with an unsorted array.
[ 7, 12, 9, 11, 3]
 Step 2: Go through the array, one value at a time. Which
value is the lowest? 3, right?
[ 7, 12, 9, 11, 3]
 Step 3: Move the lowest value 3 to the front of the array.
[ 3, 7, 12, 9, 11]
SELECTION SORT
 Step 4: Look through the rest of the values, starting with
7. 7 is the lowest value, and already at the front of the
array, so we don't need to move it.
[ 3, 7, 12, 9, 11]
 Step 5: Look through the rest of the array: 12, 9 and 11.
9 is the lowest value.
[ 3, 7, 12, 9, 11]
 Step 6: Move 9 to the front.
[ 3, 7, 9, 12, 11]
SELECTION SORT
 Step 7: Looking at 12 and 11, 11 is the lowest.
[ 3, 7, 9, 12, 11]
 Step 8: Move it to the front.
[ 3, 7, 9, 11, 12]
 Can you see what happened to the lowest value 3?
 In step 3, it has been moved to the start of the array,
where it belongs, but at that step the rest of the array
remains unsorted.
SELECTION SORT
 The Selection Sort algorithm must run through the array
again and again, each time the next lowest value is
moved in front of the unsorted part of the array, to its
correct position.
 The sorting continues until the highest value 12 is left at
the end of the array.
 This means that we need to run through the array 4
times, to sort the array of 5 values.
 Each time the algorithm runs through the array, the
remaining unsorted part of the array becomes shorter.
SELECTION SORT
Selection Sort Implementation:
1.An array with values to sort.
2.An inner loop that goes through the array, finds the
lowest value, and moves it to the front of the array. This
loop must loop through one less value each time it runs.
3.An outer loop that controls how many times the inner
loop must run. For an array with nn values, this outer
loop must run n−1n−1 times.
SELECTION SORT
my_array = [64, 34, 25, 5, 22, 11, 90, 12]
n = len(my_array)
for i in range(n-1):
min_index = i
for j in range(i+1, n):
if my_array[j] < my_array[min_index]:
min_index = j
min_value = my_array.pop(min_index)
my_array.insert(i, min_value)
print("Sorted array:", my_array)
SELECTION SORT
Selection Sort Shifting Problem
 The Selection Sort algorithm can be improved a little bit
more.
 In the code above, the lowest value element is removed,
and then inserted in front of the array.
 Each time the next lowest value array element is
removed, all following elements must be shifted one
place down to make up for the removal.
SELECTION SORT
 These shifting operation takes a lot of time, and we are
not even done yet!
 After the lowest value (5) is found and removed, it is
inserted at the start of the array, causing all following
values to shift one position up to make space for the new
value, like the image below shows.
SELECTION SORT
Solution: Swap Values!
 Instead of all the shifting, swap the lowest value (5) with
the first value (64) like below.

 We can swap values like the image above shows


because the lowest value ends up in the correct position,
and it does not matter where we put the other value we
are swapping with, because it is not sorted yet.
SELECTION SORT
def selection_sort_optimized(arr):
n = len(arr) # Example usage:
for i in range(n): arr = [5, 1, 4, 2, 8]
min_idx = i selection_sort_optimized(arr)
swapped = False print("Optimized sorted array:", arr)
for j in range(i+1, n):
if arr[j] < arr[min_idx]:
min_idx = j
# Swap only if a smaller element was found
if min_idx != i:
arr[i], arr[min_idx] = arr[min_idx], arr[i]
swapped = True
# If no swap occurred, the list is already
sorted
if not swapped:
break
SELECTION SORT
 Selection Sort sorts an array of n values.
 On average, about n2 elements are compared to find the
lowest value in each loop.
 And Selection Sort must run the loop to find the lowest
value approximately n times.
SELECTION SORT
 On average, about n2 elements are
compared to find the lowest value in
each loop.
 And Selection Sort must run the loop
to find the lowest value
approximately n times.
 We get time complexity:
INSERTION SORT
 The Insertion Sort algorithm uses one part of the array to
hold the sorted values, and the other part of the array to
hold values that are not sorted yet.
 The algorithm takes one value at a time from the
unsorted part of the array and puts it into the right place
in the sorted part of the array, until the array is sorted.
INSERTION SORT
How it works:
1.Take the first value from the unsorted part of the array.
2.Move the value into the correct place in the sorted part
of the array.
3.Go through the unsorted part of the array again as many
times as there are values.
INSERTION SORT
Manual Run Through
 Step 1: We start with an unsorted array.
[ 7, 12, 9, 11, 3]
 Step 2: We can consider the first value as the initial sorted
part of the array. If it is just one value, it must be sorted, right?
[ 7, 12, 9, 11, 3]
 Step 3: The next value 12 should now be moved into the
correct position in the sorted part of the array. But 12 is higher
than 7, so it is already in the correct position.
[ 7, 12, 9, 11, 3]
INSERTION SORT
 Step 4: Consider the next value 9.
[ 7, 12, 9, 11, 3]
 Step 5: The value 9 must now be moved into the correct
position inside the sorted part of the array, so we move 9
in between 7 and 12.
[ 7, 9, 12, 11, 3]
 Step 6: The next value is 11.
[ 7, 9, 12, 11, 3]
INSERTION SORT
 Step 7: We move it in between 9 and 12 in the sorted part
of the array.
[ 7, 9, 11, 12, 3]
 Step 8: The last value to insert into the correct position is
3.
[ 7, 9, 11, 12, 3]
 Step 9: We insert 3 in front of all other values because it is
the lowest value.
[ 3, 7, 9, 11, 12]
INSERTION SORT
 The first value is considered to be the initial sorted part
of the array.
 Every value after the first value must be compared to
the values in the sorted part of the algorithm so that it
can be inserted into the correct position.
 The Insertion Sort Algorithm must run through the array
4 times, to sort the array of 5 values because we do not
have to sort the first value.
 Each time the algorithm runs through the array, the
remaining unsorted part of the array becomes shorter
INSERTION SORT
Insertion Sort Implementation
1.An array with values to sort.
2.An outer loop that picks a value to be sorted. For an
array with n values, this outer loop skips the first value,
and must run n−1 times.
3.An inner loop that goes through the sorted part of the
array, to find where to insert the value. If the value to be
sorted is at index i, the sorted part of the array starts at
index 0 and ends at index i−1.
INSERTION SORT
my_array = [64, 34, 25, 12, 22, 11, 90, 5]
n = len(my_array)
for i in range(1,n):
insert_index = i
current_value = my_array.pop(i)
for j in range(i-1, -1, -1):
if my_array[j] > current_value:
insert_index = j
my_array.insert(insert_index,
current_value)
print("Sorted array:", my_array)
INSERTION SORT
Insertion Sort Improvement
 The problem with this way of programming it is that
when removing a value from the array, all elements
above must be shifted one index place down:
INSERTION SORT
 When inserting the removed value into the array again,
there are also many shift operations that must be done:
all following elements must shift one position up to make
place for the inserted value:

 These shifting operation can take a lot of time, especially


for an array with many elements.
INSERTION SORT
Improved Solution
 We can avoid most of these shift operations by only shifting the values
necessary:

 In the image above, first value 7 is copied, then values 11 and 12 are
shifted one place up in the array, and at last value 7 is put where
value 11 was before.
 The number of shifting operations is reduced from 12 to 2 in this case.
INSERTION SORT
my_array = [64, 34, 25, 12, 22, 11, 90, 5]
n = len(my_array)
for i in range(1,n):
insert_index = i
current_value = my_array[i]
for j in range(i-1, -1, -1):
if my_array[j] > current_value:
my_array[j+1] = my_array[j]
insert_index = j
else:
break
my_array[insert_index] = current_value
print("Sorted array:", my_array)
QUICK SORT
 As the name suggests, Quicksort is one of the fastest
sorting algorithms.
 The Quicksort algorithm takes an array of values,
chooses one of the values as the 'pivot' element, and
moves the other values so that lower values are on the
left of the pivot element, and higher values are on the
right of it.
 The last element of the array is chosen to be the pivot
element, but we could also have chosen the first
element of the array, or any element in the array really.
QUICK SORT
How it works:
1. Choose a value in the array to be the pivot element.
2. Order the rest of the array so that lower values than the
pivot element are on the left, and higher values are on the
right.
3. Swap the pivot element with the first element of the higher
values so that the pivot element lands in between the lower
and higher values.
4. Do the same operations (recursively) for the sub-arrays on
the left and right side of the pivot element.
QUICK SORT
Manual Run Through
Step 1: We start with an unsorted array.
[ 11, 9, 12, 7, 3]
Step 2: We choose the last value 3 as the pivot element.
[ 11, 9, 12, 7, 3]
Step 3: The rest of the values in the array are all greater
than 3, and must be on the right side of 3. Swap 3 with 11.
[ 3, 9, 12, 7, 11]
QUICK SORT
Step 4: Value 3 is now in the correct position. We need to sort
the values to the right of 3. We choose the last value 11 as the
new pivot element.
[ 3, 9, 12, 7, 11]
Step 5: The value 7 must be to the left of pivot value 11, and 12
must be to the right of it. Move 7 and 12.
[ 3, 9, 7, 12, 11]
Step 6: Swap 11 with 12 so that lower values 9 anf 7 are on the
left side of 11, and 12 is on the right side.
[ 3, 9, 7, 11, 12]
QUICK SORT
Step 7: 11 and 12 are in the correct positions. We choose 7 as the pivot element
in sub-array [ 9, 7], to the left of 11.
[ 3, 9, 7, 11, 12]
Step 8: We must swap 9 with 7.
[ 3, 7, 9, 11, 12]
And now, the array is sorted.
 We have already seen that last value of the array is chosen as the pivot
element, and the rest of the values are arranged so that the values lower than
the pivot value are to the left, and the higher values are to the right.
 After that, the pivot element is swapped with the first of the higher values. This
splits the original array in two, with the pivot element in between the lower and
the higher values.
QUICKSORT
To implement the Quicksort algorithm in a programming
language, we need:
 An array with values to sort.
 A quickSort method that calls itself (recursion) if the sub-
array has a size larger than 1.
 A partition method that receives a sub-array, moves
values around, swaps the pivot element into the sub-
array and returns the index where the next split in sub-
arrays happens
QUICK SORT
def quick_sort(arr):
# Base case: If the array has one or zero
elements, it is already sorted
if len(arr) <= 1:
return arr
# Choose the pivot element (middle element
in this case)
pivot = arr[len(arr) // 2]
QUICK SORT
# Create sub-arrays:
# Example usage
# left: elements less than the pivot
arr = [10, 7, 8, 9, 1, 5] # Input
# middle: elements equal to the pivot array
sorted_arr = quick_sort(arr) # Sort
# right: elements greater than the pivot
the array using quick_sort function
left = [x for x in arr if x < pivot] print("Sorted array:", sorted_arr) #
Output the sorted array
middle = [x for x in arr if x == pivot]
right = [x for x in arr if x > pivot]

# Recursively sort the left and right sub-


arrays, and concatenate them with the middle array
return quick_sort(left) + middle +
quick_sort(right)
MERGE SORT
 The Merge Sort algorithm is a divide-and-conquer algorithm that sorts
an array by first breaking it down into smaller arrays, and then
building the array back together the correct way so that it is sorted.
 Divide: The algorithm starts with breaking up the array into smaller
and smaller pieces until one such sub-array only consists of one
element.
 Conquer: The algorithm merges the small pieces of the array back
together by putting the lowest values first, resulting in a sorted array.
MERGE SORT
How it works:
1. Divide the unsorted array into two sub-arrays, half the
size of the original.
2. Continue to divide the sub-arrays as long as the current
piece of the array has more than one element.
3. Merge two sub-arrays together by always putting the
lowest value first.
4. Keep merging until there are no sub-arrays left.
MERGE SORT
MERGE SORT
Step 1: We start with an unsorted array, and we know that it splits in half until the sub-arrays
only consist of one element. The Merge Sort function calls itself two times, once for each half of
the array. That means that the first sub-array will split into the smallest pieces first.
[ 12, 8, 9, 3, 11, 5, 4]
[ 12, 8, 9] [ 3, 11, 5, 4]
[ 12] [ 8, 9] [ 3, 11, 5, 4]
[ 12] [ 8] [ 9] [ 3, 11, 5, 4]
Step 2: The splitting of the first sub-array is finished, and now it is time to merge. 8 and 9 are
the first two elements to be merged. 8 is the lowest value, so that comes before 9 in the first
merged sub-array.
[ 12] [ 8, 9] [ 3, 11, 5, 4]
Step 3: The next sub-arrays to be merged is [ 12] and [ 8, 9]. Values in both arrays are
compared from the start. 8 is lower than 12, so 8 comes first, and 9 is also lower than 12.
[ 8, 9, 12] [ 3, 11, 5, 4]
MERGE SORT
Step 4: Now the second big sub-array is split recursively.
[ 8, 9, 12] [ 3, 11, 5, 4]
[ 8, 9, 12] [ 3, 11] [ 5, 4]
[ 8, 9, 12] [ 3] [ 11] [ 5, 4]
Step 5: 3 and 11 are merged back together in the same order as they are
shown because 3 is lower than 11.
[ 8, 9, 12] [ 3, 11] [ 5, 4]
Step 6: Sub-array with values 5 and 4 is split, then merged so that 4 comes
before 5.
[ 8, 9, 12] [ 3, 11] [ 5] [ 4]
[ 8, 9, 12] [ 3, 11] [ 4, 5]
MERGE SORT
Step 7: The two sub-arrays on the right are merged. Comparisons are done to
create elements in the new merged array:
3 is lower than 4
4 is lower than 11
5 is lower than 11
11 is the last remaining value
[ 8, 9, 12] [ 3, 4, 5, 11]
Step 8: The two last remaining sub-arrays are merged. Let's look at how the
comparisons are done in more detail to create the new merged and finished
sorted array:
3 is lower than 8:
Before [ 8, 9, 12] [ 3, 4, 5, 11]
After: [ 3, 8, 9, 12] [ 4, 5, 11]
MERGE SORT
Step 9: 4 is lower than 8:
Before [ 3, 8, 9, 12] [ 4, 5, 11]
After: [ 3, 4, 8, 9, 12] [ 5, 11]
Step 10: 5 is lower than 8:
Before [ 3, 4, 8, 9, 12] [ 5, 11]
After: [ 3, 4, 5, 8, 9, 12] [ 11]
Step 11: 8 and 9 are lower than 11:
Before [ 3, 4, 5, 8, 9, 12] [ 11]
After: [ 3, 4, 5, 8, 9, 12] [ 11]
Step 12: 11 is lower than 12:
Before [ 3, 4, 5, 8, 9, 12] [ 11]
After: [ 3, 4, 5, 8, 9, 11, 12]
MERGE SORT
 To implement the Merge Sort algorithm we need:
1. An array with values that needs to be sorted.
2. A function that takes an array, splits it in two, and calls
itself with each half of that array so that the arrays are
split again and again recursively, until a sub-array only
consist of one value.
3. Another function that merges the sub-arrays back
together in a sorted way.
MERGE SORT
def mergeSort(arr):
if len(arr) <= 1:
return arr
mid = len(arr) // 2
leftHalf = arr[:mid]
rightHalf = arr[mid:]
sortedLeft = mergeSort(leftHalf)
sortedRight = mergeSort(rightHalf)
return merge(sortedLeft, sortedRight)
MERGE SORT
def merge(left, right):
result = []
i = j = 0
while i < len(left) and j <
len(right):
if left[i] < right[j]:
result.append(left[i])
i += 1
else:
result.append(right[j])
j += 1
result.extend(left[i:])
unsortedArr = [3, 7, 6, -10, 15, 23.5, 55, -
result.extend(right[j:]) 13]
sortedArr = mergeSort(unsortedArr)
LINEAR SEARCH
 The Linear Search algorithm searches through an array
and returns the index of the value it searches for.
 A big difference between sorting algorithms and
searching algorithms is that sorting algorithms modify
the array, but searching algorithms leave the array
unchanged.
LINEAR SEARCH
How it works:
1. Go through the array value by value from the start.
2. Compare each value to check if it is equal to the value
we are looking for.
3. If the value is found, return the index of that value.
4. If the end of the array is reached and the value is not
found, return -1 to indicate that the value was not
found.
LINEAR SEARCH
Step 1: We start with an array of random values.
[ 12, 8, 9, 11, 5, 11]
Step 2: We look at the first value in the array, is it equal
to 11?
[ 12, 8, 9, 11, 5, 11]
Step 3: We move on to the next value at index 1, and
compare it to 11 to see if it is equal.
[ 12, 8, 9, 11, 5, 11]
LINEAR SEARCH
Step 4: We check the next value at index 2.
[ 12, 8, 9, 11, 5, 11]
Step 5: We move on to the next value at index 3. Is it equal
to 11?
[ 12, 8, 9, 11, 5, 11]
Every value is checked from the start of the array to see if
the value is equal to 11, the value we are trying to find.
When the value is found, the searching is stopped, and the
index where the value is found is returned.
LINEAR SEARCH
 To implement the Linear Search algorithm we need:
1. An array with values to search through.
2. A target value to search for.
3. A loop that goes through the array from start to end.
4. An if-statement that compares the current value with the
target value, and returns the current index if the target
value is found.
5. After the loop, return -1, because at this point we know
the target value has not been found.
LINEAR SEARCH
def linearSearch(arr, targetVal):
for i in range(len(arr)):
if arr[i] == targetVal:
return i
return -1
arr = [3, 7, 2, 9, 5]
targetVal = 9
result = linearSearch(arr, targetVal)
if result != -1:
print("Value",targetVal,"found at index",result)
else:
BINARY SEARCH
 The Binary Search algorithm searches through an array
and returns the index of the value it searches for.
 The Binary Search algorithm works by checking the
value in the center of the array. If the target value is
lower, the next value to check is in the center of the left
half of the array.
 This way of searching means that the search area is
always half of the previous search area, and this is why
the Binary Search algorithm is so fast.
BINARY SEARCH
How it works:
1. Check the value in the center of the array.
2. If the target value is lower, search the left half of the
array. If the target value is higher, search the right half.
3. Continue step 1 and 2 for the new reduced part of the
array until the target value is found or until the search
area is empty.
4. If the value is found, return the target value index. If the
target value is not found, return -1.
BINARY SEARCH
Manual Run Through (We will search for value 11)
Step 1: We start with an array.
[ 2, 3, 7, 7, 11, 15, 25]
Step 2: The value in the middle of the array at index 3, is it equal
to 11?
[ 2, 3, 7, 7, 11, 15, 25]
Step 3: 7 is less than 11, so we must search for 11 to the right of
index 3. The values to the right of index 3 are [ 11, 15, 25]. The
next value to check is the middle value 15, at index 5.
[ 2, 3, 7, 7, 11, 15, 25]
BINARY SEARCH
Step 4: 15 is higher than 11, so we must search to the left
of index 5. We have already checked index 0-3, so index 4
is only value left to check.
[ 2, 3, 7, 7, 11, 15, 25]
BINARY SEARCH
To implement the Binary Search algorithm we need:
1. An array with values to search through.
2. A target value to search for.
3. A loop that runs as long as left index is less than, or equal to, the right
index.
4. An if-statement that compares the middle value with the target value, and
returns the index if the target value is found.
5. An if-statement that checks if the target value is less than, or larger than,
the middle value, and updates the "left" or "right" variables to narrow
down the search area.
6. After the loop, return -1, because at this point we know the target value
has not been found.
BINARY SEARCH
def binarySearch(arr, targetVal):
left = 0
right = len(arr) - 1
while left <= right:
mid = (left + right) // 2
if arr[mid] == targetVal: myArray = [1, 3, 5, 7, 9, 11, 13, 15, 17, 19]
myTarget = 15
return mid result = binarySearch(myArray, myTarget)
if arr[mid] < targetVal: if result != -1:
print("Value",myTarget,"found at index",
left = mid + 1
result)
else: else:
right = mid - 1 print("Target not found in array.")

return -1

You might also like