Chapter 3 - Simple Sorting and Searching
Chapter 3 - Simple Sorting and Searching
go to step 8
3. Simple Sorting and Searching Step 7: Print element not found
Algorithms Step 8: Exit
Searching Pseudocode
Searching is a process of looking for a
specific element in a list of items or
procedure linear_search (list, value)
determining that the item is not in the list.
There are two simple searching algorithms:
for each item in the list
Sequential Search, and
Binary Search if match item == value
3.1.1 Linear Search (Sequential
Search) return the item's location
A linear search looks down a list, one item end if
at a time, without jumping. In complexity
terms this is an O(n) search the time taken to end for
search the list gets bigger at the same rate as
the list does. Linear search is a very simple end procedure
search algorithm. In this type of search, a
sequential search is made over all items one Example Implementation:
by one. Every item is checked and if a match
is found then that particular item is int Linear_Search(int list[], int key)
returned, otherwise the search continues {
till the end of the data collection. int index=0;
int found=0;
Algorithm of linear search do{
Loop through the array starting at the first if(key==list[index])
element until the value of target matches one found=1;
of the array elements. If a match is not else
found, return 1. index++;
Time is proportional to the size of input (n) }while(found==0&&index<n);
and we call this time complexity O(n) if(found==0)
index=-1;
Algorithm return index;
}
3.1.2Binary Search
A binary search is searching start with the
middle of a sorted list, and see whether that's
greater than or less than the value you're
looking for, which determines whether the
Linear Search (Array A, Value x)
value is in the first or second half of the list.
Step 1: Set i to 1
Jump to the half way through the sub list,
Step 2: if i > n then go to step 7
and compare again etc. This is pretty much
Step 3: if A[i] = x then goes to step 6
how humans typically look up a word in a
Step 4: Set i to i + 1
dictionary (although we use better heuristics,
Step 5: Go to Step 2
obviously - if you're looking for "cat" you
don't start off at "M"). In complexity terms
this is an O(log n) search - the number of
search operations grows more slowly than How Binary Search Works?
the list does, because you're halving the
"search space" with each operation .This For a binary search to work, it is mandatory
search algorithm works on the principle of for the target array to be sorted. We shall
divide and conquer. This searching Learn the process of binary search with a
algorithm works only for an ordered list. pictorial example. The following is our
The basic idea is: sorted
Locate midpoint of array to array and let us assume that we need to
search search the location of value 31 using
Determine if target is in lower half or binary
upper half of an array. Search.
If in lower half, make this half the
array to search
If in the upper half, make this half
First, we shall determine half of the array by
the array to search
using this formula -
mid = low + (high - low) / 2
Loop back to step 1 until the size of the Here it is, 0 + (9 - 0 ) / 2 = 4 (integer value
array to search is one, and this element does of 4.5). So, 4 is the mid of the array.
not match, in which case return 1.
The computational time for this
algorithm is proportional to log2 n
Therefore the time complexity is O(log n)
Now we compare the value stored at
location 4, with the value being searched,
Pseudo code i.e. 31. We find that the value at location 4 is
27, which is not a match. As the value is
Procedure binary search
greater than 27 and we have a sorted array,
A sorted array
N size of array so we also know that the target value must
X value to be searched be in the upper portion of the array.
Set lower Bound = 1
Set upper Bound = n
While x not found
If upper Bound < lower Bound
EXIT: x does not exist.
Set midpoint = lower Bound + (upper We change our low to mid + 1 and find the
Bound - lower Bound) / 2 new mid value again.
If A[midpoint] < x low = mid + 1
Set lower Bound = midpoint + 1 mid = low + (high - low) / 2
If A[midpoint] > x Our new mid is 7 now. We compare the
Set upper Bound = midpoint - 1 value stored at location 7 with our target
If A[midpoint] = x value 31.
EXIT: x found at location midpoint
End while
End procedure
The pseudo code of binary search algorithms
should look like this
The value stored at location 7 is not a match; As an example, suppose you were looking
rather it is less than what we are looking for. for U in an A-Z list of letters (index 0-25;
So, the value must be in the lower part from we're looking for the value at index 20).
this location. A linear search would ask:
list[0] == 'U'? No.
list[1] == 'U'? No.
list[2] == 'U'? No.
list[3] == 'U'? No.
list[4] == 'U'? No.
Hence, we calculate the mid again. This
list[5] == 'U'? No.
time it is 5.
... list[20] == 'U'? Yes, Finished.
Algorithm
Pseudo Code
A Array list
N Size of A
X Target Value
Procedure Interpolation_Search()
Broadly, we can understand divide-and-
Set Lo 0
conquer approach in a three-step process.
Set Mid -1
Set Hi N-1
While X does not match Divide/Break
if Lo equals to Hi OR A[Lo] equals to A[Hi]
EXIT: Failure, Target not found This step involves breaking the problem into
end if smaller sub-problems. Sub-problems should
Set Mid = Lo + ((Hi - Lo) / (A[Hi] - A[Lo])) represent a part of the original problem. This
* (X - A[Lo]) step generally takes a recursive approach to
if A[Mid] = X divide the problem until no sub-problem is
EXIT: Success, Target found at Mid further divisible. At this stage, sub-
else problems
if A[Mid] < X become atomic in nature but still represent
Set Lo to Mid+1 some part of the actual problem.
else if A[Mid] > X
Set Hi to Mid-1 Conquer/Solve
end if
end if This step receives a lot of smaller sub-
End While problems to be solved. Generally, at this
End Procedure level, the
problems are considered 'solved' on their
Divide and Conquer own.
In divide and conquer approach, the problem
Merge/Combine
in hand, is divided into smaller sub-
When the smaller sub-problems are solved,
problems
this stage recursively combines them until
and then each problem is solved
they formulate a solution of the original
independently. When we keep on dividing
problem. This algorithmic approach works
the sub-
recursively and conquer & merge steps
problems into even smaller sub-problems,
works so close that they appear as one.
we may eventually reach a stage where
Examples
no
The following computer algorithms are
more division is possible. Those "atomic"
based on divide-and-conquer programming
smallest possible sub-problems (fractions)
approach
are
Merge Sort
Quick Sort In-place Sorting and Not-in-place Sorting
Binary Search
There are various ways available to solve Sorting algorithms may require some extra
any computer problem, but the mentioned space for comparison and temporary storage
are a good example of divide and conquer of few data elements. These algorithms do
approach. not require any extra space and sorting is
said
to happen in-place, or for example, within
3.2. Sorting Algorithms the array itself. This is called in-place
sorting.
Bubble sort is an example of in-place
Sorting is one of the most important
sorting.
operations performed by computers. Sorting
is a process of reordering a list of items in
However, in some sorting algorithms, the
either increasing or decreasing order. The
program requires space which is more than
following are simple sorting algorithms used
or equal to the elements being sorted.
to sort small-sized lists.
Sorting which uses equal or more space is
Have an array you need to put in order? called not-in-place sorting . Merge-sort is
Keeping business records and want to sort an example of not-in-place sorting.
them by ID number or last name of client?
Then you'll need a sorting algorithm. To Stable and Not Stable Sorting
understand the more complex and efficient
sorting algorithms, it's important to first If a sorting algorithm, after sorting the
understand the simpler, but slower contents, does not change the sequence of
algorithms. similar content in which they appear, it is
called stable sorting .
Sorting refers to arranging data in a
particular format. Sorting algorithm
specifies the way
to arrange data in a particular order.
Most common orders are in numerical or
Lexicographical order.
The importance of sorting lies in the fact If a sorting algorithm, after sorting the
that data searching can be optimized to a contents, changes the sequence of similar
very high level, if data is stored in a sorted content
manner. Sorting is also used to represent in which they appear, it is called unstable
data in more readable formats. sorting .
Following are some of the
examples of sorting in real-life
scenarios:
Telephone Directory
The telephone directory stores the telephone
numbers of people sort ed by their names, so
that the names can be searched easily.
end procedure
However, swapping makes 27 and 10
unsorted.
How Insertion Sort Works?
We take an unsorted array for our
example.
Hence, we swap them too.
Insertion sort compares the first two Again we find 14 and 10 in an unsorted
elements. order.
We know then that 10 is smaller 35. Hence This does not change the sequence of
they are not sorted. appearance of items in the original. Now we
divide these two arrays into halves.
After the final merging, the list should look var c as array
like this -
while ( a and b have elements )
if ( a[0] > b[0] )
add b[0] to the end of c
Now we should learn some programming remove b[0] from b
aspects of merge sorting. else
add a[0] to the end of c
Algorithm remove a[0] from a
Merge sort keeps on dividing the list into end if
equal halves until it can no more be divided. end while
By definition, if it is only one element in the
list, it is sorted. Then, merge sort combines while ( a has elements )
the smaller sorted lists keeping the new list add a[0] to the end of c
sorted too. remove a[0] from a
Step 1 if it is only one element in the list it end while
is already sorted, return.
Step 2 divide the list recursively into two while ( b has elements )
halves until it can no more be add b[0] to the end of c
divided. remove b[0] from b
Step 3 merge the smaller lists into new list end while
in sorted order.
Pseudocode return c
We shall now see the pseudo codes for
merge sort functions. As our algorithms end procedure
point out two main functions divide &
merge.Merge sort works with recursion and Quick Sort
we shall see our implementation in the same Quick sort is a highly efficient sorting
way. algorithm and is based on partitioning of
array of
data into smaller arrays. A large array is
partitioned into two arrays one of which
holds
values smaller than the specified value, say
pivot, based on which the partition is made
and another array holds values greater than
the pivot value. Quick Sort Pivot Pseudocode
Quick sort partitions an array and then calls The pseudocode for the above algorithm can
itself recursively twice to sort the two be derived as -
resulting
subarrays. This algorithm is quite function partitionFunc(left, right, pivot)
efficient for large-sized data sets as its leftPointer = left -1
average and rightPointer = right
worst case complexity are of O(nlogn),
where n is the number of items. while True do
Partition in Quick Sort while A[++leftPointer] < pivot do
//do-nothing
Following animated representation explains end while
how to find the pivot value in an array.
while rightPointer > 0 && A[--
rightPointer] > pivot do
//do-nothing
end while
if right-left <= 0
return
else
pivot = A[right]
partition = partitionFunc(left, right,
pivot)
quickSort(left,partition-1)
quickSort(partition+1,right)
end if
end procedure
END