ch#2
ch#2
SIMPLE SEARCHING
AND
SORTING ALGORITHMS
32
Why do we study sorting and searching algorithms?
These algorithms are the most common and
useful tasks operated by computer system.
Computers spend a lot of time for searching and
sorting.
1. Simple Searching algorithms
Searching:- is a process of finding an element
in a list of items or determining that the item is
not in the list.
A search method looks for a key, arrives by
parameter. By convention, the method will
return the index of the element corresponding to
the key or, if unsuccessful, the value -1.
33
There are two simple searching algorithms:
⚫ Sequential, and Binary Search
2.1.1. Sequential Searching (Linear)
Sequential search looks at elements, one at a time, from the first in
the list until a match for the target is found.
The most natural way of searching an item. Easy to understand and
implement.
Algorithm:
In a linear search, we start with top (beginning) of the list, and
compare the element at top with the key.
If we have a match, the search terminates and the index number is
returned. If not, we go on the next element in the list.
If we reach the end of the list without finding a match, we return -1.
Pseudo code
Loop through the array starting at the first element until the value
of target matches one of the array elements.
If a match is not found, return –1.
else return -1 index. (-1 shows that the key is not in the list).
The computational time for this algorithm is proportional to38
log2 n Therefore the time complexity is O(log n)
39
S P A C E C OMPLEXITY O(1) 40
2.2. Sorting Algorithms
Sorting is one of the most important operations
performed by computers.
Sorting is a process of reordering a list of items in either
increasing or decreasing order.
Sorting data (i.e., placing the data into some particular
order, such as ascending or descending) is one of the
most important computing applications.
It is important due mainly to the fact that searching a
list is much faster if the list is sorted.
The following are simple sorting algorithms used to sort
small-sized lists.
⚫ Insertion Sort
⚫ Selection Sort
⚫ Bubble Sort 41
1. Insertion Sort
The insertion sort works just like its name suggests - it
inserts each item into its proper place in the final list.
The simplest implementation of this requires two list
structures - the source list and the list into which sorted
items are inserted.
To save memory, most implementations use an in-place
sort that works by moving the current item past the
already sorted items and repeatedly swapping it with
the preceding item until it is in place.
It's the most instinctive type of sorting algorithm.
17
18
19
2.2.3. Bubble Sort
Bubble sort is the simplest algorithm to implement and the slowest
algorithm on very large inputs.
Basic Idea: Loop through array from i=0 to n and swap adjacent
elements if they are out of order.
20
21
22
23