Download as pdf or txt
Download as pdf or txt
You are on page 1of 16

Searching….

Riddhi and Ananya


What is searching

Searching in computer science, is the process of executing an


algorithm with the aim of finding a target value within the data set.

Two types of searching:

1. Linear search
2. Binary search
Linear Search

Iterating over an array one element at a time until the search value is found.
Steps

1. Compare the current element with the target


a. If element = target
b. Output the element
c. Output its position
2. Move onto the next element
3. If element not found, output “not found”
Binary Search

Comparing the middle element of a sorted array with the search value
repeatedly in order to find the search value.
Steps

1. Go to middle element of the array


a. If current element = target
b. Output element and position
2. Compare the left element to the target
a. If target < element
b. Disregard the right hand side of the array
c. Repeat the steps
3. Compare the right element to the target
a. If target > element
b. Disregard the left hand side of the array
c. Repeat the steps
Linear VS Binary

Linear Binary

Unsorted or sorted data set Sorted data set required

Effective for small data sets or Effective for large data sets
when search value is the first
value in the data set

O(n) running time O(log n) running time


Question [2 + 11 = 13 marks]
Data set: [2, 5, 7, 9, 10, 12, 13, 14, 17, 19, 21, 22, 28]
If the value 17 must be searched for in the array, which searching method
is better to use and why?

Write the algorithm for the above data set, where the user inputs a value
they wish to find. The algorithm must output:

1. Whether the user value inputted was found in the array


2. If found, what position it was found at
3. Output the number of steps taken when executing the algorithm.

Include appropriate output statements and variable names.


In one sentence, explain each variable and data structure used.
Mark scheme

a) 1 mark for identifying the correct search


1 mark for stating why (binary search would take less steps)

b) 2 marks for initialising all variables and data structures correctly and
using appropriate variable names
1 mark correct loop structure
3 marks for correct comparisons (if else statements)
1 mark for correct output
1 mark for calculating and outputting position
1 mark for calculating and outputting steps
2 marks for explaining all variables and data structures used
Sorting
Bubble sort

Continuously comparing two adjacent elements in an array and


swapping them if they are out of order, until the whole array is sorted.

O(n2) running time


Selection sort

Iterating over the array and swapping the smallest element of the
unsorted array with the last element of the sorted side.

O(n log n) running time

You might also like