Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
20 views

Chapter - 3 - Searching and Sorting Algorithms

Here is a C++ program that implements various sorting algorithms and compares their efficiency on different unsorted data sets: #include <iostream> using namespace std; // Function prototypes void bubbleSort(int arr[], int n); void selectionSort(int arr[], int n); void insertionSort(int arr[], int n); // Function to count comparisons int comparisons = 0; // Function to count swaps int swaps = 0; // Driver code int main() { int arr1[] = {5, 4, 3, 2, 1}; // Already sorted - best case int size1 = sizeof(arr1)/sizeof(arr1[0

Uploaded by

Firomsa Dine
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views

Chapter - 3 - Searching and Sorting Algorithms

Here is a C++ program that implements various sorting algorithms and compares their efficiency on different unsorted data sets: #include <iostream> using namespace std; // Function prototypes void bubbleSort(int arr[], int n); void selectionSort(int arr[], int n); void insertionSort(int arr[], int n); // Function to count comparisons int comparisons = 0; // Function to count swaps int swaps = 0; // Driver code int main() { int arr1[] = {5, 4, 3, 2, 1}; // Already sorted - best case int size1 = sizeof(arr1)/sizeof(arr1[0

Uploaded by

Firomsa Dine
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 22

Chapter 3

Searching and Sorting Algorithms

1
Content
This Chapter Covers:
 Sequential(linear) Search
 Binary search
 Bubble sort
 Selection sort
 Insertion sort

2
Why we need sorting and searching algorithms?
they are the most common & useful tasks in any software development
they take more than 25% of running time of computers task
Example:
Searching documents over the internet
Searching files and folders in a hard disk
Sorting students by their name, year and so on
Sorting file, search results by file name, date created and so on
Deleting and recording data from a database Table

3
Searching Algorithm
The act of searching for a piece of information in a list is one of the fundamental
algorithms in software development .
Searching: is a process of locating a particular element present in a given set of
elements.

A search algorithm: is an algorithm that accepts an argument ‘a’ and tries to


find an element whose value is ‘a’.
It is possible that the search for a particular element in a set is unsuccessful if
that element does not exist.
Two searching algorithms :-
Sequential/Linear search
Binary search

4
Linear Searching
The linear search algorithm searches each element in an array sequentially.
If the search key does not match an element in the array, the algorithm tests each
element and, when the end of the array is reached, informs the user that the search key
is not present.
Step1. If the search key is in the array, the algorithm tests each element until it finds
one that matches the search key and returns the index of that element.
Step2. If after checking every array element, the method determines that the search key
does not match any element in the array, the function returns -1.
Step3. If there are duplicate values in the array, linear search returns the index of the
first element in the array that matches the search key.

5
Sequential Searching

Example :-Search the element (25)

6
Binary Searching
The binary search algorithm is more efficient than the linear search algorithm, but it
requires that the array must be sorted.
The first iteration of this algorithm tests the middle element in the array. If this
matches the search key, the algorithm ends.
Each iteration tests the middle value of the remaining portion of the array, called a
subarray.
The algorithm ends by either finding an element that matches the search key or
reducing the subarray to zero size.

7
Binary Searching
Algorithm:
1. Divide the list into halves
2. see which half of the list the key belongs
3. repeat 1 and 2 until only one element remains
4. if the remaining element is equal to search key then found =true else key not
found.
 Simplified form of binary search algorithms
1st assign first and last
2nd calculate middle= first + last/2
Case1, if array[middle]<key first=middle+1, last=last
Case 2, if array[middle]>key first=first, last=middle-1
Case 3, if key==array[middle] print position or index of
Key 8
Binary Searching

9
Binary Searching
Exercise

10
Sorting Algorithms
For searching, sorting is important
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 order.
The importance of sorting lies in the fact that data searching can be optimized to a very
high level, if data is stored in a sorted manner.
Sorting is also used to represent data in more readable formats

11
Bubble Sort Algorithms
It a method which uses the interchanging of adjacent pair of element in the
array.
traverse from left and compare adjacent elements and the higher one is placed at
right side.
In this way, the largest element is moved to the rightmost end at first.
This process is then continued to find the second largest and place it and so on
until the data is sorted.

12
Example Array element= 7,2,9,6,4
Algorithms:
• Implementations: Example sort the following array using bubble sort
(int data[])
loop through i= 0 to N-1
loop through j = 0 to N – i-1
Single pass
if data[j] >data[j+1] i=0
swap data[j] and data[j+1]

Example
Continue
15 16 6 8 5
until sorted

13
Quiz #1 – Lab-5%
1.Write a c++ program to search a specific letter in a
given string using linear search algorithm and return the
index of that letter?
Hint: use your name as a string
2.Write binary search algorithm to search specific element of
a given array element to return the index of that element, the
element must be sorted in descending order first.

All input accept from end user;


14
Selection Sort Algorithms
The selection sort algorithm sorts an array by repeatedly finding the
minimum element (considering ascending order) from unsorted part and
putting it at the beginning
It is in many ways like both simple and bubble algorithm.
Rather than swapping the neighbors continuously as the algorithm traverses
the sub array to be sorted, as done in the bubble sort case, this algorithm
finds the minimum element of the sub array and swaps it with the pivot
elements.
The algorithm maintains two subarrays in a given array.
The subarray which is already sorted.
Remaining subarray which is unsorted.

15
Selection Sort Algorithms
 The smallest element is selected from unsorted element and exchange with element in the beginning unsorted
element
i=0
 Loop through the array from i = 0 to N – 1.
J=1
Min=i
 Select the smallest element in the array from i = 1 to N - 1. 7 4 10 8 3 1
 Swap this value with value at position i.
Pass 1 1 4 10 8 3 7
Example
Algorithms:
void SelectionSort(int data[]) Pass 2 1 3 10 8 4 7
int smallest
loop through i =0 to N -1 Pass 3 1 3 4 8 10 7
smallest  i
loop through j  i+1 to N Pass 4 1 3 4 7 10 8
if data[j] < data[smallest]
smallest  j
Pass 1 1 3 4 7 8 10
swap data[i] and data[smallest]);
Example
Implementation:

int min;
for(int i=0;i<6;i++){
min=i;
for(int j=i+1;j<6;j++){
if(A[j]<A[min])
min=j;}
int temp=A[min];
A[min]=A[i];
A[i]=temp;
cout<<A[i]<<endl;}}

17
Insertion Sort Algorithms
As each element in the list is examined it is put into its proper place
among the elements that have been examined ( and put in correct
order).
When the last element is put into its proper position the list is sorted
and the algorithm is done.
It behaves in the worst case like the inefficient bubble sort and selection
sort algorithms.
But in many average case it performs better.

18
19
Implementation
• Implementations:
Int a[],
Int n,temp;
For(i=1;i<n;i++){
Temp=a[i]
j=i-1;
While (j>=0&&a[j]>temp)
{a[j+1]=a[j];
j--}
A[j+1]=temp;

20
Exercise - I
Write a C++ program that will implement all of the sorting algorithms. The
program should accept different unsorted data items from user and sort
using all algorithms and should tell which algorithm is efficient for that
unsorted data items. (Hint use how many comparison and swaps are done so
the one with the smaller number of swap and comparison number is
considered as an efficient algorithm for that data items.)

21

???
End!!!!!!!!

22

You might also like