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

UNIT5 Part1 Sorting&Searching

The document discusses searching and sorting algorithms in C programming. It defines an algorithm as a step-by-step procedure to solve a problem on a computer. Searching algorithms like linear search and binary search are used to find a value in a list. Linear search has O(n) time complexity while binary search has O(log n) time complexity but requires the list to be sorted. Common sorting algorithms mentioned are selection sort, bubble sort, and insertion sort which arrange elements in a data structure in a systematic order.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
42 views

UNIT5 Part1 Sorting&Searching

The document discusses searching and sorting algorithms in C programming. It defines an algorithm as a step-by-step procedure to solve a problem on a computer. Searching algorithms like linear search and binary search are used to find a value in a list. Linear search has O(n) time complexity while binary search has O(log n) time complexity but requires the list to be sorted. Common sorting algorithms mentioned are selection sort, bubble sort, and insertion sort which arrange elements in a data structure in a systematic order.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 15

UNIT-5

I-B. TECH-I-SEMESTER- C PROGRAMMING AND DATA STRUCTURES

Part1: Searching Algorithms

Introduction to Algorithms:

What is an Algorithm?

“An algorithm is step by step procedure to solve a problem on a computer.”

Significance of Algorithms:

 Algorithms used to convert our problem into step-by-step statements.


 These statements can be converted into a computer programming instruction
which form a program.
 This program is executed by a computer to produce a solution.
 The following procedure shows in below Figure:

What is the Performance Analysis of an algorithm?

The performance analysis of an algorithm is the process of calculating space and time
complexity required by that algorithm.

Performance of an algorithm’s measures by the following parameters.

a) Space Complexity: Space(memory) required to complete the task of that


algorithm. Generally, it includes program space and data space.
b) Time Complexity: Time required to complete the task of that algorithm.
Searching Algorithms

What is search?

Search is a process of finding a value in a list of values. In other words, searching is the
process of locating given value position in a list of values.

There two types of searching algorithms in C programming language:

1. Linear Search (Sequential Search)


2. Binary Search
1. Linear Search Algorithm (Sequential Search Algorithm)
 This is the simplest of all searching techniques.
 In this technique, an ordered or unordered list will be searched one by one from
the beginning until the desired element is found.
 If the desired element is found in the list, then the search is successful
otherwise unsuccessful.
 Suppose there are ‘n’ elements list, on an average you need [(n+1)/2]
comparisons to search an element.
 The time complexity of linear search is O(n).

Algorithm to implement Linear Search:

Step 1: Read the search element from the user.

Step 2: Compare the search element with the first element in the list.

Step 3: If both are matched, then display "Given element is found!!!" and terminate
the function.

Step 4: If both are not matched, then compare search element with the next element
in the list.

Step 5: If both are not matched, then compare search element with the next element
in the list.

Step 6: If last element in the list also doesn't match, then display "Element is not
found!!!" and terminate the function.
1. (a) C Program to implementation of Linear Search Algorithm(non-recursive):

#include<stdio.h>
#include<conio.h>
void main(){
int list[20],size,i,sElement;
printf("Enter size of the list: ");
scanf("%d",&size);
printf("Enter any %d integer values: ",size);
for(i = 0; i < size; i++)
scanf("%d",&list[i]);
printf("Enter the element to be Search: ");
scanf("%d",&sElement);
// Linear Search Logic
for(i = 0; i < size; i++)
{
if(sElement == list[i])
{
printf("Element is found at %d index", i);
break;
}
}
if(i == size)
printf("Given element is not found in the list!!!");
getch();
}

Output:
(b) C Program to implementation of Linear Search Algorithm (Recursive):

# include <stdio.h>
# include <conio.h>
void linear_search(int a[], int data, int position, int n)
{
if (position < n)
{
if(a[position] == data)
printf("\n Data Found at %d ", position);
else
linear_search(a, data, position + 1, n);
}
else
printf("\n Data not found");
}
void main()
{
int a[25], i, n, data;
//
printf("\n Enter the number of elements: ");
scanf("%d", &n);
printf("\n Enter the elements: ");
for(i = 0; i < n; i++)
{
scanf("%d", &a[i]);
}
printf("\n Enter the element to be seached: ");
scanf("%d", &data);
linear_search(a, data, 0, n);//
}
2. Binary Search Algorithm:
 Binary Search is a searching algorithm used in a sorted array
by repeatedly dividing the search interval in half.
 The idea of binary search is to use the information that the array is sorted
and reduce the time complexity to O (Log n).
 The binary search cannot be used for a list of elements arranged in random
order.
 This search process starts comparing the search element with the middle
element in the list.
 If both are matched, then the result is "element found". Otherwise, we check
whether the search element is smaller or larger than the middle element in
the list.
 If the search element is smaller, then we repeat the same process for the
left sub list of the middle element. If the search element is larger, then we
repeat the same process for the right sub list of the middle element.
 We repeat this process until we find the search element in the list or until
we left with a sub list of only one element.
 And if that element also doesn't match with the search element, then the
result is "Element not found in the list".

Algorithm to implement Binary Search:

Step 1: Read the search element from the user.


Step 2: Find the middle element in the sorted list.
Step 3: Compare the search element with the middle element in the sorted list.
Step 4: If both are matched, then display "Given element is found!!!" and terminate
the function.
Step 5: If both are not matched, then check whether the search element is smaller
or larger than the middle element.
Step 6: If both are not matched, then check whether the search element is smaller
or larger than the middle element.
Step 7: If the search element is larger than middle element, repeat steps 2, 3, 4
and 5 for the right sub list of the middle element.
Step 8: Repeat the same process until we find the search element in the list or
until sub list contains only one element.
Step 9: If that element also doesn't match with the search element, then display
"Element is not found in the list!!!" and terminate the function.
C Program to implementation of Binary Search Algorithm (Non-Recursive):

#include<stdio.h>
void main()
{
int first, last, middle, size, i, sElement, list[100];
printf("Enter the size of the list: ");
scanf("%d",&size);
printf("Enter %d integer values in Assending order\n", size);
for (i = 0; i < size; i++)
scanf("%d",&list[i]);
printf("Enter value to be search: ");
scanf("%d", &sElement);
first = 0;
last = size - 1;
middle = (first+last)/2;
while (first <= last)
{
if (list[middle] < sElement)
first = middle + 1;
else if (list[middle] == sElement) {
printf("Element found at index %d.\n",middle);
break;
}
else
last = middle - 1;

middle = (first + last)/2;


}
if (first > last)
printf("Element Not found in the list.");
}

Output:
(b) C Program to implementation of Binary Search Algorithm (Recursive):

# include <stdio.h>
void bin_search(int a[], int data, int low, int high)
{
int mid ;
if( low <= high)
{
mid = (low + high)/2;
if(a[mid] == data)
printf("\n Element found at location: %d ", mid + 1);
else
{
if(data < a[mid])
bin_search(a, data, low, mid-1);
else
bin_search(a, data, mid+1, high);
}
}
else
printf("\n Element not found");
}
void main()
{
int a[25], i, n, data;
printf("\n Enter the number of elements: ");
scanf("%d", &n);
printf("\n Enter the elements in ascending order: ");
for(i = 0; i < n; i++)
scanf("%d", &a[i]);
printf("\n Enter the element to be searched: ");
scanf("%d", &data);
bin_search(a, data, 0, n-1);
}
Differences between Linear Search and Binary Search:

Linear Search Algorithm Binary Search Algorithm


In linear search input data need not to In binary search input data need to be
be in sorted. in sorted order.
It is also called sequential search. It is also called half-interval search.
The time complexity of linear The time complexity of binary
search O(n). search O(log n).
Multidimensional array can be used. Only single dimensional array is used.
Linear search performs equality Binary search performs ordering
comparisons. comparisons.
It is less complex. It is more complex.
It is very slow process. It is very fast process.
SORTING

“Sorting allows an efficient arrangement of elements within a given data structure.”

It is a way in which the elements are organized systematically for some purpose. For
example, a dictionary in which words is arranged in alphabetical order and telephone
director in which the subscriber names are listed in alphabetical order. There are
many sorting techniques out of which we study the following:

1. Selection sort
2. Bubble sort
3. Insertion sort
4. Quick sort
1. Selection Sort

Selection Sort algorithm is used to arrange a list of elements in a particular order


(Ascending or Descending).

Algorithm for Selection Sort:


The selection sort algorithm is performed using the following steps...

Step 1: Select the first element of the list (i.e., Element at first position in the list).

Step 2: Compare the selected element with all the other elements in the list.

Step 3: In every comparison, if any element is found smaller than the selected
element (for Ascending order), then both are swapped.

Step 4: Repeat the same procedure with element in the next position in the list till
the entire list is sorted.

Complexity of the Selection Sort Algorithm:

To sort an unsorted list with 'n' number of elements, we need to make,

((n-1) + (n-2) + (n-3) +......+1) = (n (n-1))/2 number of comparisons in the worst case.

If the list is already sorted, then it requires 'n' number of comparisons.

Worst Case: O(n2)

Best Case: Ω(n2)

Average Case: Θ(n2)


(a) Non-recursive program for Selection sort:

#include<stdio.h>
void main()
{
int size,i,j,temp,list[100];
printf("Enter the size of the List: ");
scanf("%d",&size);
printf("Enter %d integer values: ",size);
for(i=0; i<size; i++)
scanf("%d",&list[i]);
//Selection sort logic
for(i=0; i<size; i++){
for(j=i+1; j<size; j++)
{
if(list[i] > list[j])
{
temp=list[i];
list[i]=list[j];
list[j]=temp;
}
}
}
printf("List after sorting is: ");
for(i=0; i<size; i++)
printf(" %d",list[i]);
}
(b) Recursive program for Selection sort:

/* C Program to Implement Selection Sort using Recursion */

#include <stdio.h>
void selection(int [], int, int, int, int);
int main()
{
int list[30], size, temp, i, j;
printf("Enter the size of the list: ");
scanf("%d", &size);
printf("Enter the elements in list:\n");
for (i = 0; i < size; i++)
{
scanf("%d", &list[i]);
}
printf(" The list before sorting \n");
for (i = 0; i < size; i++)
{
printf("%d ", list[i]);
}
selection(list, 0, 0, size, 1);
printf("The sorted list in ascending order is\n");
for (i = 0; i < size; i++)
{
printf("%d ", list[i]);
}
return 0;
}
void selection(int list[], int i, int j, int size, int flag)
{
int temp;
if (i < size - 1)
{
if (flag)
{
j = i + 1;
}
if (j < size)
{
if (list[i] > list[j])
{
temp = list[i];
list[i] = list[j];
list[j] = temp;
}
selection(list, i, j + 1, size, 0);
}
selection(list, i + 1, 0, size, 1);
}
}
2. Bubble Sort:

Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping
the adjacent elements if they are in the wrong order. This algorithm is not suitable
for large data sets as its average and worst-case time complexity is quite high.

(a) C program to implement Bubble sort using for loop:

#include <stdio.h>

int main()
{
int arr[50], num, i, j, temp;

printf("Please Enter the Number of Elements you want in the array: ");

scanf("%d", &num);

printf("Please Enter the Value of Elements: ");

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

scanf("%d", &arr[i]);

for(i = 0; i < num - 1; i++)


{
for(j = 0; j < num - i - 1; j++)
{
if(arr[j] > arr[j + 1])
{
temp = arr[j];

arr[j] = arr[j + 1];

arr[j + 1] = temp;

}
}
}

printf("Array after implementing bubble sort: ");

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


{

printf("%d ", arr[i]);

return 0;

}
(b) C program to implement Bubble sort using functions:

#include <stdio.h>

void bubbleSortExample(int arr[], int num)


{

int x, y, temp;

for(x = 0; x < num - 1; x++)


{
for(y = 0; y < num - x - 1; y++)
{
if(arr[y] > arr[y + 1])
{
temp = arr[y];
arr[y] = arr[y + 1];
arr[y + 1] = temp;
}
}
}
}

int main()
{

int arr[50], n, x;

printf("Please Enter the Number of Elements you want in the array: ");

scanf("%d", &n);

printf("Please Enter the Value of Elements: ");

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

scanf("%d", &arr[x]);

bubbleSortExample(arr, n);

printf("Array after implementing bubble sort: ");

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


{

printf("%d ", arr[x]);

return 0;

}
INSERTION SORT
Define insertion sort:

Insertion sort is a simple sorting algorithm that works like the way you sort playing
cards in your hands. In insertion sort algorithm, every iteration moves an element
from unsorted portion to sorted portion until all the elements are sorted in the list.

Characteristics of Insertion Sort:


 This algorithm is one of the simplest algorithms with simple implementation.
 Basically, Insertion sort is efficient for small data values.
 Insertion sort is adaptive in nature, i.e., it is appropriate for data sets which are
already partially sorted.

Algorithm for Insertion sort:

Step 1: Assume that first element in the list is in sorted portion and all the remaining
elements are in unsorted portion.

Step 2: Take first element from the unsorted portion and insert that element into the
sorted portion in the order specified.

Step 3: Repeat the above process until all the elements from the unsorted portion are
moved into the sorted portion.

Complexity of the Insertion Sort Algorithm:

To sort an unsorted list with 'n' number of elements, we need to make,

(1+2+3+......+n-1) = (n (n-1))/2 number of comparisons in the worst case.

If the list is already sorted, then it requires 'n' number of comparisons.

C Program to implement insertion sort algorithm:

#include<stdio.h>
void main()
{
int size, i, j, temp, list[100];
printf("Enter the size of the list: ");
scanf("%d", &size);
printf("Enter %d integer values: ", size);
for (i = 0; i < size; i++)
scanf("%d", &list[i]);
//Insertion sort logic
for (i = 1; i < size; i++)
{
temp = list[i];
j = i - 1;
while ((temp < list[j]) && (j >= 0))
{
list[j + 1] = list[j];
j = j - 1;
}
list[j + 1] = temp;
}
printf("List after Sorting is: ");
for (i = 0; i < size; i++)
printf(" %d", list[i]);
}
Differences between Selection sort, Bubble sort and Insertion sort
Selection Sort Bubble Sort Insertion sort

Selection Sort algorithm is used to Bubble Sort is the simplest sorting In insertion sort algorithm, every
arrange a list of elements in a algorithm that works by repeatedly iteration moves an element from
particular order. swapping the adjacent elements if unsorted portion to sorted portion
they are in the wrong order. until all the elements are sorted in the
list.
2
Time Complexity - Best case: O (N ) Time Complexity - Best case: O (N) Time Complexity - Best case: O (N)

Advantages: Advantages:
Advantages:

1. It can also be used on list structures 1. It can be easily computed.


1. It is the simplest sorting approach.
that make add and remove efficient, 2. Best case complexity is
2. Best case complexity is of O(N) [for
such as a linked list. Just remove of O(N) while the array is already
optimized approach] while the
the smallest element of unsorted sorted.
array is sorted.
part and end at the end of sorted 3. Number of swaps reduced than
3. Stable sort: does not change the
part. bubble sort.
relative order of elements with
2. The number of swaps 4. For smaller values of N, insertion
equal keys.
reduced. O(N) swaps in all cases. sort performs efficiently like other
4. In-Place sort.
3. In-Place sort. quadratic sorting algorithms.
5. Stable sort.
Disadvantages: Disadvantages: 6. Adaptive: total number of steps is
reduced for partially sorted array.
1. Time complexity in all cases 1. Bubble sort is comparatively slower 7. In-Place sort.
is O(N2), no best-case scenario. algorithm.
Disadvantages:
2. It requires n-squared number of 2. Poor efficiency for large elements of
steps for sorting n elements. array. 1. It is generally used when the value
of N is small. For larger values of
3. It is not scalable. N, it is inefficient.
2. Similar as selection sort it requires
n-squared number of steps for
sorting n elements.

You might also like