CH2 - Simple Sorting and Searching Algorithm
CH2 - Simple Sorting and Searching Algorithm
Chapter Two
Simple Sorting and Searching
Algorithms
Simple Searching Algorithms
• Searching is a process of looking for a specific element in a list of
items or determining that the item is not in the list.
Example
• Array numlist contains: 17, 23, 5, 11, 2, 29,3 Searching for the
value 11, linear search examines 17, 23, 5, and 11 Searching for
the value 7, linear search examines 17, 23, 5, 11, 2, 29, and 3
Linear Search Algorithm
set found to false;
set position to -1;
set index to 0
while index < number of elements and found is false
if list[index] is equal to search value
found = true
position = index
end if
add 1 to index
end while
return position
Implementation of Linear Search Algorithm
Int searchList (int list[], int numElems, int value)
{ int index = 0;
Int position = -1;
// To record position of search value
Bool found = false;
// flag to indicate if value was found
While(index < numElems && !found) {
If( list[index] == value) // if the value is found
{ found = true; // set the flag
Position = index; // record the value’s subscript
} index ++;
// go to the next element
} return position;
// return the position or -1
}
Example that Implements Linear Search
int main()
{
int i, value,found=-1, list[]={65,20,10,55,32,12,50,99};
cout<<"enter the number to be searched\n":
cin>> value;
for(int i=0; i<8; i++)
{
if(value==list[i])
{
found= i+1;
break; }
}
if (found == -1)
{
cout<<"thw element "<<value<<" is not found";
}
else
{
cout<< " the position of "<<value<<"->"<<found;
}}
Efficiency of Linear Search
Advantage
• It is simple.
• It is easy to understand
• Easy to implement Best Case
• Does not require the array to be in item found at the beginning: O(1)
order Worst Case
item found at the end: O(n)
Disadvantage Average Case
• its inefficiency Arithmetic average: n+1/2
• Ineffcient (slow): for array of N
elements, examines N/2 elements on
average for value in array,
• N elements for value not in array
Binary Search
– Insertion Sort
– Selection Sort
– Bubble Sort
Insertion Sort
• The insertion sort works just like its name suggests - it inserts each
item into its proper place in the final list.
Basic Idea:
Loop through the array from i=0 to n-1.
Basic Idea:
Loop through array from i=0 to n and swap adjacent elements if they are
out of order.
Implementation:
void bubble_sort(list[])
{ Analysis of Bubble Sort
int i,j,temp;
How many comparisons?
for(i=0;i<n; i++){
(n-1)+(n-2)+…+1= O(n2)
for(j=n-1;j>i; j--){
How many swaps?
if(list[j]<list[j-1]){
(n-1)+(n-2)+…+1= O(n2)
temp=list[j];
Space?
list[j]=list[j-1];
In-place algorithm.
list[j-1]=temp;
}//swap adjacent elements
}//end of inner loop
}//end of outer loop
}//end of bubble_sort