0% found this document useful (0 votes)
4 views

Unit-IV notes.doc

The document provides an overview of searching and sorting algorithms, specifically linear and binary search methods, as well as selection sort, bubble sort, insertion sort, quick sort, and merge sort. It details the processes and pseudocode for linear and binary searches, highlighting their features and time complexities. Additionally, it explains selection and bubble sort algorithms with examples and code snippets for better understanding.

Uploaded by

sandeep bhukya
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

Unit-IV notes.doc

The document provides an overview of searching and sorting algorithms, specifically linear and binary search methods, as well as selection sort, bubble sort, insertion sort, quick sort, and merge sort. It details the processes and pseudocode for linear and binary searches, highlighting their features and time complexities. Additionally, it explains selection and bubble sort algorithms with examples and code snippets for better understanding.

Uploaded by

sandeep bhukya
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 30

Unit-IV

Searching and Sorting- Searching-linear and binary search methods. Sorting- selection
sort, bubble sort, insertion sort, quick sort, merge sort

INTRODUCTION TO SEARCHING ALGORITHMS


Searching is an operation or a technique that helps finds the place of a given element or
value in the list. Any search is said to be successful or unsuccessful depending upon whether the
element that is being searched is found or not. Some of the standard searching technique that is
being followed in data structure is listed below:

1. Linear Search

2. Binary Search
LINEAR SEARCH
Linear search is a very basic and simple search algorithm. In Linear search, we search an
element or value in a given array by traversing the array from the starting, till the desired
element or value is found.
It compares the element to be searched with all the elements present in the array and when
the element is matched successfully, it returns the index of the element in the array, else it
return -1.
Linear Search is applied on unsorted or unordered lists, when there are fewer elements in a
list. For Example,
Linear Search

10 14 19 26 27 31 33 35
42 44
=
3
Algorithm 3
Linear Search ( Array A, Value x)
Step 1: Set i to 1
Step 2: if i > n then go to step 7
Step 3: if A[i] = x then go to step 6
Step 4: Set i to i + 1
Step 5: Go to Step 2
Step 6: Print Element x Found at index i and go to step 8
Step 7: Print element not found
Step 8: Exit
Pseudocode
procedure linear_search (list, value)
for each item in the list
if match item == value
return the item‟s
location end if
end for
end procedure

Features of Linear Search Algorithm


1. It is used for unsorted and unordered small list of elements.
2. It has a time complexity of O(n), which means the time is linearly dependent on
the number of elements, which is not bad, but not that good too.
3. It has a very simple implementation.

#include <stdio.h>
int main()
{
int array[100], search, c, n;

printf("Enter number of elements in array\n");


scanf("%d", &n);

printf("Enter %d integer(s)\n", n);

for (c = 0; c < n; c++)


scanf("%d", &array[c]);

printf("Enter a number to search\n");


scanf("%d", &search);
for (c = 0; c < n; c++)
{
if (array[c] == search) /* If required element is found */
{
printf("%d is present at location %d.\n", search, c+1);
break;
}
}
if (c == n)
printf("%d isn't present in the array.\n", search);

return 0;
}

BINARY SEARCH
Binary Search is used with sorted array or list. In binary search, we follow the following
steps:
1. We start by comparing the element to
be searched with the element in the
middle of the list/array.
2. If we get a match, we return the index of the
middle element.
3. If we do not get a match, we check
whether the element to be searched is
less or greater than in value than the
middle element.
4. If the element/number to be searched
is greater in value than the middle
number, then we pick the elements on
the right side of the middle
element(as the list/array is sorted,
hence on the right, we will have all
the numbers greater than the middle
number), and start again from the step
1.
5. If the element/number to be searched
is lesser in value than the middle
number, then we pick the elements on
the left side of the middle element,
and start again from the step 1.
Binary Search is useful when there are large number
of elements in an array and they are
sorted. So a necessary condition for Binary search to work is that the list/array should be sorted.
Features of Binary Search
1. It is great to search through large sorted arrays.
2. It has a time complexity of O(log n) which is a very good time complexity. It has a
simple implementation.
Binary search is a fast search algorithm with run-time complexity of Ï(log n). This search
algorithm works on the principle of divide and conquers. For this algorithm to work properly,
the data collection should be in the sorted form.
Binary search looks for a particular item by comparing the middle most item of the
collection. If a match occurs, then the index of item is returned. If the middle item is greater
than the item, then the item is searched in the sub-array to the left of the middle item. Otherwise,
the item is searched for in the sub-array to the right of the middle item. This process continues
on the sub- array as well until the size of the sub array reduces to zero.
How Binary Search Works?
For a binary search to work, it is mandatory for the target array to be sorted. We shall
learn the process of binary search with a pictorial example. The following is our sorted array
and let us assume that we need to search the location of value 31 using binary search.

10 14 19 26 27 31 33 35 42 44
0 1 2 3 4 5 6 7 8 9
First, we shall determine half of the array by using this formula -
mid = low + (high - low) / 2
Here it is, 0 + (9 - 0 ) / 2 = 4 (integer value of 4.5). So, 4 is the mid of the array.

10 14 19 26 27 31 33 35 42 44
0 1 2 3 4 5 6 7 8 9
Now we compare the value stored at location 4, with the value being searched, i.e. 31. We
find that the value at location 4 is 27, which is not a match. As the value is greater than 27 and
we have a sorted array, so we also know that the target value must be in the upper portion of the
array.

10 14 19 26 27 31 33 35 42 44
0 1 2 3 4 5 6 7 8 9
We change our low to mid + 1 and find the new mid value again.
low = mid + 1
mid = low + (high - low) / 2
Our new mid is 7 now. We compare the value stored at location 7 with our target value 31.

10 14 19 26 27 31 33 35 42 44
0 1 2 3 4 5 6 7 8 9
The value stored at location 7 is not a match, rather it is more than what we are looking
for. So, the value must be in the lower part from this location.

10 14 19 26 27 31 33 35 42 44
0 1 2 3 4 5 6 7 8 9
Hence, we calculate the mid again. This time it is 5.

10 14 19 26 27 31 33 35 42 44
0 1 2 3 4 5 6 7 8 9
We compare the value stored at location 5 with our target value. We find that it is a match.

10 14 19 26 27 31 33 35 42 44
0 1 2 3 4 5 6 7 8 9
We conclude that the target value 31 is stored at location 5.
Binary search halves the searchable items and thus reduces the count of comparisons to be
made to very less numbers.
Pseudocode
The pseudocode of binary search algorithms should look like this “
Procedure binary_search
#include <stdio.h>
int main()
{
int c, first, last, middle, n, search, array[100];

printf("Enter number of elements\n");


scanf("%d", &n);

printf("Enter %d integers\n", n);

for (c = 0; c < n; c++)


scanf("%d", &array[c]);

printf("Enter value to find\n");


scanf("%d", &search);

first = 0;
last = n - 1;
middle = (first+last)/2;

while (first <= last) {


if (array[middle] < search)
first = middle + 1;
else if (array[middle] == search) {
printf("%d found at location %d.\n", search, middle+1);
break;
}
else
last = middle - 1;

middle = (first + last)/2;


}
if (first > last)
printf("Not found! %d isn't present in the list.\n", search);

return 0;
}

Selection Sort

The selection Sort is assaulting algorithm that works by finding the smallest number from the
array and then placing it to the first position. the next array that is to be traversed will start
from index next to the position where the smallest number is placed.
Let's take an example to make this concept more clear.
We have an array {6, 3, 8, 12, 9} in this array the smallest element is 3. So we will place 3 at the
first position, after this the array will look like {3, 6, 8, 12, 9}. Now we will again find the
smallest number but this time we will not consider 3 in our search because it is in its place.
Finding the next smallest element that is 6, creating an array with 6 at the second position and
then again searching in the array till the array is sorted.
Working of selection Sort algorithm−
the following steps are followed by the selection Sort algorithm
Let's take an array {20, 12 , 23, 55 ,21}
● Set the first element of the array as minimum.
Minimum = 20
● Compare the minimum with the next element, if it is smaller than minimum assign this
element as minimum. Do this till the end of the array.
Comparing with 12 : 20 > 12 , minimum = 12
Comparing with 23 : 12 < 23 , minimum = 12
Comparing with 55 : 12 < 55 , minimum = 12
Comparing with 21 : 12 < 21 , minimum = 12
● Place the minimum at the first position( index 0) of the array.
Array = {12, 20 ,23, 55, 21}
● for the next iteration, start sorting from the first unsorted element i.e. the element next
to where the minimum is placed.
Array = {12, 20 ,23, 55, 21}
Searching starts from 20, next element where minimum is placed.
Iteration 2 :
Minimum = 20
Comparing with 23 : 20 < 23 , minimum = 20
Comparing with 55 : 20 < 55 , minimum = 20
Comparing with 21 : 20 < 21 , minimum = 20
Minimum in place no change,
Array = {12, 20 ,23, 55, 21}
Iteration 3 :
Minimum = 23.
Comparing with 55 : 23 < 55 , minimum = 23
Comparing with 21 : 23 > 21 , minimum = 21
Minimum is moved to index = 2
Array = {12, 20, 21, 55, 23}
Iteration 4 :
Minimum = 55
Comparing with 23 : 23 < 55 , minimum = 23
Minimum in moved to index 3 Array = {12, 20, 21, 23, 55}
Example
#include <stdio.h>
int main() {
int arr[10]={6,12,0,18,11,99,55,45,34,2};
int n=10;
int i, j, position, swap;
for (i = 0; i < (n - 1); i++) {
position = i;
for (j = i + 1; j < n; j++) {
if (arr[position] > arr[j])
position = j;
}
if (position != i) {
swap = arr[i];
arr[i] = arr[position];
arr[position] = swap;
}
}
for (i = 0; i < n; i++)
printf("%d\t", arr[i]);
return 0;
}
Output
0 2 6 11 12 18 34 45 55 99
Bubble sort

Bubble sort works on the repeatedly swapping of adjacent elements until they are not in the
intended order. It is called bubble sort because the movement of array elements is just like the
movement of air bubbles in the water. Bubbles in water rise up to the surface; similarly, the
array elements in bubble sort move to the end in each iteration.
Working of Bubble sort Algorithm

Now, let's see the working of Bubble sort Algorithm.


To understand the working of bubble sort algorithm, let's take an unsorted array. We are taking
a short and accurate array, as we know the complexity of bubble sort is O(n2).

Let the elements of array are -

First Pass

Sorting will start from the initial two elements. Let compare them to check which is greater.

Here, 32 is greater than 13 (32 > 13), so it is already sorted. Now, compare 32 with 26.

Here, 26 is smaller than 36. So, swapping is required. After swapping new array will look like -

Now, compare 32 and 35.

Here, 35 is greater than 32. So, there is no swapping required as they are already sorted.

Now, the comparison will be in between 35 and 10.


Here, 10 is smaller than 35 that are not sorted. So, swapping is required. Now, we reach at the
end of the array. After first pass, the array will be -

Now, move to the second iteration.

Second Pass

The same process will be followed for second iteration.

Here, 10 is smaller than 32. So, swapping is required. After swapping, the array will be -

Now, move to the third iteration.

Third Pass

The same process will be followed for third iteration.


Here, 10 is smaller than 26. So, swapping is required. After swapping, the array will be -

Now, move to the fourth iteration.

Fourth pass

Similarly, after the fourth iteration, the array will be -

Hence, there is no swapping required, so the array is completely sorted.

1. #include<stdio.h>
2. void print(int a[], int n) //function to print array elements
3. {
4. int i;
5. for(i = 0; i < n; i++)
6. {
7. printf("%d ",a[i]);
8. }
9. }
10. void bubble(int a[], int n) // function to implement bubble sort
11. {
12. int i, j, temp;
13. for(i = 0; i < n; i++)
14. {
15. for(j = i+1; j < n; j++)
16. {
17. if(a[j] < a[i])
18. {
19. temp = a[i];
20. a[i] = a[j];
21. a[j] = temp;
22. }
23. }
24. }
25. }
26. void main ()
27. {
28. int i, j,temp;
29. int a[5] = { 10, 35, 32, 13, 26};
30. int n = sizeof(a)/sizeof(a[0]);
31. printf("Before sorting array elements are - \n");
32. print(a, n);
33. bubble(a, n);
34. printf("\nAfter sorting array elements are - \n");
35. print(a, n);
36. }

Output

Insertion sort

Algorithm

The simple steps of achieving the insertion sort are listed as follows -

Step 1 - If the element is the first element, assume that it is already sorted. Return 1.

Step2 - Pick the next element, and store it separately in a key.

Step3 - Now, compare the key with all elements in the sorted array.

Step 4 - If the element in the sorted array is smaller than the current element, then move to the
next element. Else, shift greater elements in the array towards the right.

Step 5 - Insert the value.

Step 6 - Repeat until the array is sorted.


Working of Insertion sort Algorithm

Now, let's see the working of the insertion sort Algorithm.

To understand the working of the insertion sort algorithm, let's take an unsorted array. It will be
easier to understand the insertion sort via an example.

Let the elements of array are -

Initially, the first two elements are compared in insertion sort.

Here, 31 is greater than 12. That means both elements are already in ascending order. So, for
now, 12 is stored in a sorted sub-array.

Now, move to the next two elements and compare them.

Here, 25 is smaller than 31. So, 31 is not at correct position. Now, swap 31 with 25. Along with
swapping, insertion sort will also check it with all elements in the sorted array.

For now, the sorted array has only one element, i.e. 12. So, 25 is greater than 12. Hence, the
sorted array remains sorted after swapping.

Now, two elements in the sorted array are 12 and 25. Move forward to the next elements that
are 31 and 8.
Both 31 and 8 are not sorted. So, swap them.

After swapping, elements 25 and 8 are unsorted.

So, swap them.

Now, elements 12 and 8 are unsorted.

So, swap them too.

Now, the sorted array has three items that are 8, 12 and 25. Move to the next items that are 31
and 32.

Hence, they are already sorted. Now, the sorted array includes 8, 12, 25 and 31.
Move to the next elements that are 32 and 17.

17 is smaller than 32. So, swap them.

Swapping makes 31 and 17 unsorted. So, swap them too.

Now, swapping makes 25 and 17 unsorted. So, perform swapping again.

Now, the array is completely sorted.

#include <stdio.h>

void insert(int a[], int n) /* function to sort an aay with insertion sort */
{
int i, j, temp;
for (i = 1; i < n; i++) {
temp = a[i];
j = i - 1;

while(j>=0 && temp <= a[j]) /* Move the elements greater than temp to one position ahead fr
om their current position*/
{
a[j+1] = a[j];
j = j-1;
}
a[j+1] = temp;
}
}

void printArr(int a[], int n) /* function to print the array */


{
int i;
for (i = 0; i < n; i++)
printf("%d ", a[i]);
}

int main()
{
int a[] = { 12, 31, 25, 8, 32, 17 };
int n = sizeof(a) / sizeof(a[0]);
printf("Before sorting array elements are - \n");
printArr(a, n);
insert(a, n);
printf("\nAfter sorting array elements are - \n");
printArr(a, n);

return 0;
}

Output:

Quick Sort

This algorithm follows the divide and conquer approach. Divide and conquer is a technique of
breaking down the algorithms into subproblems, then solving the subproblems, and combining
the results back together to solve the original problem.
Divide: In Divide, first pick a pivot element. After that, partition or rearrange the array into two
sub-arrays such that each element in the left sub-array is less than or equal to the pivot element
and each element in the right sub-array is larger than the pivot element.

Conquer: Recursively, sort two subarrays with Quicksort.

Combine: Combine the already sorted array.

Quicksort picks an element as pivot, and then it partitions the given array around the picked
pivot element. In quick sort, a large array is divided into two arrays in which one holds values
that are smaller than the specified value (Pivot), and another array holds the values that are
greater than the pivot.

After that, left and right sub-arrays are also partitioned using the same approach. It will
continue until the single element remains in the sub-array.

Choosing the pivot

Picking a good pivot is necessary for the fast implementation of quicksort. However, it is typical
to determine a good pivot. Some of the ways of choosing a pivot are as follows -

o Pivot can be random, i.e. select the random pivot from the given array.
o Pivot can either be the rightmost element of the leftmost element of the given array.
o Select median as the pivot element.

Algorithm

Algorithm:

1. QUICKSORT (array A, start, end)


2. {
3. 1 if (start < end)
4. 2{
5. 3 p = partition(A, start, end)
6. 4 QUICKSORT (A, start, p - 1)
7. 5 QUICKSORT (A, p + 1, end)
8. 6}
9. }
Working of Quick Sort Algorithm

Now, let's see the working of the Quicksort Algorithm.

To understand the working of quick sort, let's take an unsorted array. It will make the concept
more clear and understandable.

Let the elements of array are -

In the given array, we consider the leftmost element as pivot. So, in this case, a[left] = 24,
a[right] = 27 and a[pivot] = 24.

Since, pivot is at left, so algorithm starts from right and move towards left.

Now, a[pivot] < a[right], so algorithm moves forward one position towards left, i.e. -
Now, a[left] = 24, a[right] = 19, and a[pivot] = 24.

Because, a[pivot] > a[right], so, algorithm will swap a[pivot] with a[right], and pivot moves to
right, as -

Now, a[left] = 19, a[right] = 24, and a[pivot] = 24. Since, pivot is at right, so algorithm starts from
left and moves to right.

As a[pivot] > a[left], so algorithm moves one position to right as -


Now, a[left] = 9, a[right] = 24, and a[pivot] = 24. As a[pivot] > a[left], so algorithm moves one
position to right as -

Now, a[left] = 29, a[right] = 24, and a[pivot] = 24. As a[pivot] < a[left], so, swap a[pivot] and
a[left], now pivot is at left, i.e. -
Since, pivot is at left, so algorithm starts from right, and move to left. Now, a[left] = 24, a[right]
= 29, and a[pivot] = 24. As a[pivot] < a[right], so algorithm moves one position to left, as -

Now, a[pivot] = 24, a[left] = 24, and a[right] = 14. As a[pivot] > a[right], so, swap a[pivot] and
a[right], now pivot is at right, i.e. -

Now, a[pivot] = 24, a[left] = 14, and a[right] = 24. Pivot is at right, so the algorithm starts from
left and move to right.
Now, a[pivot] = 24, a[left] = 24, and a[right] = 24. So, pivot, left and right are pointing the same
element. It represents the termination of procedure.

Element 24, which is the pivot element is placed at its exact position.

Elements that are right side of element 24 are greater than it, and the elements that are left
side of element 24 are smaller than it.

Now, in a similar manner, quick sort algorithm is separately applied to the left and right
sub-arrays. After sorting gets done, the array will be -

#include<stdio.h>
void quicksort(int number[25],int first,int last){
int i, j, pivot, temp;
if(first<last){
pivot=first;
i=first;
j=last;
while(i<j){
while(number[i]<=number[pivot]&&i<last)
i++;
while(number[j]>number[pivot])
j--;
if(i<j){
temp=number[i];
number[i]=number[j];
number[j]=temp;
}
}
temp=number[pivot];
number[pivot]=number[j];
number[j]=temp;
quicksort(number,first,j-1);
quicksort(number,j+1,last);
}
}
int main(){
int i, count, number[25];
printf("How many elements are u going to enter?: ");
scanf("%d",&count);
printf("Enter %d elements: ", count);
for(i=0;i<count;i++)
scanf("%d",&number[i]);
quicksort(number,0,count-1);
printf("Order of Sorted elements: ");
for(i=0;i<count;i++)
printf(" %d",number[i]);
return 0;
}
Output
When the above program is executed, it produces the following output −
How many elements are u going to enter?: 10
Enter 10 elements: 2 3 5 7 1 9 3 8 0 4
Order of Sorted elements: 0 1 2 3 3 4 5 7 8 9

Merge Sort

Merge sort is similar to the quick sort algorithm as it uses the divide and conquer approach to
sort the elements. It is one of the most popular and efficient sorting algorithm. It divides the
given list into two equal halves, calls itself for the two halves and then merges the two sorted
halves. We have to define the merge() function to perform the merging.

The sub-lists are divided again and again into halves until the list cannot be divided further.
Then we combine the pair of one element lists into two-element lists, sorting them in the
process. The sorted two-element pairs is merged into the four-element lists, and so on until we
get the sorted list.

Algorithm

In the following algorithm, arr is the given array, beg is the starting element, and end is the last
element of the array.

1. MERGE_SORT(arr, beg, end)


2.
3. if beg < end
4. set mid = (beg + end)/2
5. MERGE_SORT(arr, beg, mid)
6. MERGE_SORT(arr, mid + 1, end)
7. MERGE (arr, beg, mid, end)
8. end of if
9.
10. END MERGE_SORT
The important part of the merge sort is the MERGE function. This function performs the
merging of two sorted sub-arrays that are A[beg…mid] and A[mid+1…end], to build one
sorted array A[beg…end]. So, the inputs of the MERGE function are A[], beg, mid, and end.

The implementation of the MERGE function is given as follows -

1. /* Function to merge the subarrays of a[] */


2. void merge(int a[], int beg, int mid, int end)
3. {
4. int i, j, k;
5. int n1 = mid - beg + 1;
6. int n2 = end - mid;
7.
8. int LeftArray[n1], RightArray[n2]; //temporary arrays
9.
10. /* copy data to temp arrays */
11. for (int i = 0; i < n1; i++)
12. LeftArray[i] = a[beg + i];
13. for (int j = 0; j < n2; j++)
14. RightArray[j] = a[mid + 1 + j];
15.
16. i = 0, /* initial index of first sub-array */
17. j = 0; /* initial index of second sub-array */
18. k = beg; /* initial index of merged sub-array */
19.
20. while (i < n1 && j < n2)
21. {
22. if(LeftArray[i] <= RightArray[j])
23. {
24. a[k] = LeftArray[i];
25. i++;
26. }
27. else
28. {
29. a[k] = RightArray[j];
30. j++;
31. }
32. k++;
33. }
34. while (i<n1)
35. {
36. a[k] = LeftArray[i];
37. i++;
38. k++;
39. }
40.
41. while (j<n2)
42. {
43. a[k] = RightArray[j];
44. j++;
45. k++;
46. }
47. }
Working of Merge sort Algorithm

Now, let's see the working of merge sort Algorithm.

To understand the working of the merge sort algorithm, let's take an unsorted array. It will be
easier to understand the merge sort via an example.

Let the elements of array are -

According to the merge sort, first divide the given array into two equal halves. Merge sort keeps
dividing the list into equal parts until it cannot be further divided.

As there are eight elements in the given array, so it is divided into two arrays of size 4.

Now, again divide these two arrays into halves. As they are of size 4, so divide them into new
arrays of size 2.

Now, again divide these arrays to get the atomic value that cannot be further divided.
Now, combine them in the same manner they were broken.

In combining, first compare the element of each array and then combine them into another
array in sorted order.

So, first compare 12 and 31, both are in sorted positions. Then compare 25 and 8, and in the list
of two values, put 8 first followed by 25. Then compare 32 and 17, sort them and put 17 first
followed by 32. After that, compare 40 and 42, and place them sequentially.

In the next iteration of combining, now compare the arrays with two data values and merge
them into an array of found values in sorted order.

Now, there is a final merging of the arrays. After the final merging of above arrays, the array will
look like -

Now, the array is completely sorted.

Implementation of merge sort

Program: Write a program to implement merge sort in C language.


#include <stdio.h>

#define max 10

int a[11] = { 10, 14, 19, 26, 27, 31, 33, 35, 42, 44, 0 };
int b[10];

void merging(int low, int mid, int high) {


int l1, l2, i;

for(l1 = low, l2 = mid + 1, i = low; l1 <= mid && l2 <= high; i++) {
if(a[l1] <= a[l2])
b[i] = a[l1++];
else
b[i] = a[l2++];
}

while(l1 <= mid)


b[i++] = a[l1++];

while(l2 <= high)


b[i++] = a[l2++];

for(i = low; i <= high; i++)


a[i] = b[i];
}

void sort(int low, int high) {


int mid;

if(low < high) {


mid = (low + high) / 2;
sort(low, mid);
sort(mid+1, high);
merging(low, mid, high);
} else {
return;
}
}

int main() {
int i;

printf("List before sorting\n");


for(i = 0; i <= max; i++)
printf("%d ", a[i]);

sort(0, max);

printf("\nList after sorting\n");

for(i = 0; i <= max; i++)


printf("%d ", a[i]);
}
If we compile and run the above program, it will produce the following result −
Output
List before sorting
10 14 19 26 27 31 33 35 42 44 0
List after sorting
0 10 14 19 26 27 31 33 35 42 44

You might also like