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

Module-1 (Searching & Sorting)

Uploaded by

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

Module-1 (Searching & Sorting)

Uploaded by

Arepally Sukumar
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 27

Searching: Linear and Binary

Search is a process of finding a value in a list of values.


Linear Search:

• Linear search algorithm finds given element in a list of elements with O(n) time
complexity where n is total number of elements in the list.

• This search process starts comparing of search element with the first element in
the list.

• If both are matching then results with element found otherwise search element is
compared with next element in the list.

• If both are matched, then the result is "element found".

• Otherwise, repeat the same with the next element in the list until search element
is compared with last element in the list, if that last element also doesn't match,
then the result is "Element not found in the list".

Algorithm for 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 matching, then display "Given element found!!!" and terminate
the function

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

Step 5: Repeat steps 3 and 4 until the search element is compared with the last
element in the list.

Step 6: If the last element in the list is also doesn't match, then display "Element
not found!!!" and terminate the function.

Example:
Consider the following list of element and search element...
Linear Search Program (Non-recursive):

#include<stdio.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!!!");
}

OUTPUT:
Enter size of the list: 8
Enter any 8 integer values:
65 20 10 55 32 12 50 99
Enter the element to be Search: 12
Element is found at 5 index
Linear Search Program (Recursive):

/*Write a C program Linear Search Using Recursive Functions*/


#include<stdio.h>
int linear(int[],int,int);
main()
{
int a[100],n,i,key;
printf("Enter Size");
scanf("%d",&n);
printf("Enter %d elements",n);
for(i=0;i<n;i++)
scanf("%d",&a[i]);
printf("The array elements");
for(i=0;i<n;i++)
printf("%4d",a[i]);
printf("\nEnter element to search");
scanf("%d",&key);
i=linear(a,n-1,key);
if(i!=-1)
printf("\nThe element %d found at %d location",key,i+1);
else
printf("\nThe element %d is not found",key);

int linear(int x[100],int n,int key)


{
if(n<=0)
return -1;
if(x[n]==key)
return n;
else
return linear(x,n-1,key);
}

OUTPUT:
Enter Size8
Enter 8 elements
65 20 10 55 32 12 50 99
The array elements 65 20 10 55 32 12 50 99
Enter element to search12
The element 12 found at 6 location
BINARY SEARCH:
• Binary search algorithm finds given element in a list of elements with O(log
n) time complexity where n is total number of elements in the list.

• The binary search algorithm can be used with only sorted list of element.
That means, binary search can be used only with list of element which are
already arraged in a order.

• The binary search can not be used for list of element which are in random
order.

• This search process starts comparing of 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 left
sublist of the middle element.

• If the search element is larger, then we repeat the same process for right
sublist of the middle element.

• We repeat this process until we find the search element in the list or until
we left with a sublist 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 for 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 matching, then display "Given element found!!!" and terminate
the function
Step 5: If both are not matching, then check whether the search element is
smaller or larger than middle element.

Step 6: If the search element is smaller than middle element, then repeat steps 2,
3, 4 and 5 for the left sublist of the middle element.

Step 7: If the search element is larger than middle element, then repeat steps 2,
3, 4 and 5 for the right sublist of the middle element.

Step 8: Repeat the same process until we find the search element in the list or
until sublist contains only one element.

Step 9: If that element also doesn't match with the search element, then display
"Element not found in the list!!!" and terminate the function.

Example
Consider the following list of element and search element...
//Binary Search program for Non-recursive
#include <stdio.h>
int main()
{
int c, first, last, middle, n, key, 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", &key);
first = 0;
last = n - 1;
middle = (first+last)/2;
while (first <= last)
{
if (array[middle] < key)
first = middle + 1;
else if (array[middle] == key)
{
printf("%d found at location %d.\n", key, middle+1);
break;
}
else
last = middle - 1;
middle = (first + last)/2;
}
if (first > last)
printf("Not found! %d is not present in the list.\n", key);

return 0;
}
Output:
Enter number of elements
9
Enter 9 integers
10 12 20 32 50 55 65 80 99
Enter value to find
80
80 found at location 8.

//Binary Search using recursion


#include<stdio.h>
int binsearch(int[], int, int, int);
int main()
{
int n, i, key, position;
int low, high, list[100];

printf("\nEnter the total number of elements");


scanf("%d",&n);

printf("\nEnter the elements of list :");


for (i = 0; i < n; i++)
{
scanf("%d", &list[i]);
}

low = 0;
high = n - 1;

printf("\nEnter element to be searched : ");


scanf("%d", &key);

position = binsearch(list, key, low, high);

if (position != -1) {
printf("\nNumber present at %d", (position + 1));
} else
printf("\n The number is not present in the list");
return (0);
}
// Binary Search function
int binsearch(int a[], int x, int low, int high)
{
int mid;
if (low > high)
return -1;
mid = (low + high) / 2;
if (x == a[mid])
{
return (mid);
}
else if (x < a[mid])
{
binsearch(a, x, low, mid - 1);
}
else
{
binsearch(a, x, mid + 1, high);
}
}
OUTPUT:
Enter the total number of elements9
Enter the elements of list :
10 12 20 32 50 55 65 80 99
Enter element to be searched : 80
Number present at 8

1.Bubble Sort

✓ Bubble sort is a simple sorting algorithm.

✓ This sorting algorithm is comparison-based algorithm in which each pair of


adjacent elements is compared and the elements are swapped if they are
not in order.

✓ This algorithm is not suitable for large data sets as its average and worst
case complexity are of Ο(n2) where n is the number of items.
//Implementation of bubble sort

#include<stdio.h>

int main( )

int a[100];

int i, j, temp, n ;

printf("how many numbers you want to sort : \n");

scanf("%d",&n);

printf("Enter %d number values you want to sort\n", n);

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

scanf("%d",&a[j]);

for(j=1;j<n;j++)

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

if(a[i]>a[i+1])

temp=a[i];

a[i]=a[i+1];

a[i+1]=temp;

printf ( "\n\nArray after sorting:\n");

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

printf ( "%d\t", a[i] );

}
OUTPUT:

how many numbers you want to sort :

11

Enter 11 number values you want to sort

11 8 9 7 5 555 28 22 18 19 35

Array after sorting:

5 7 8 9 11 18 19 22 28 35 555

2.SELECTION SORT

✓ Selection sort is a simple sorting algorithm. This sorting algorithm is an in-


place comparison-based algorithm in which the list is divided into two
parts, the sorted part at the left end and the unsorted part at the right end.

✓ Initially, the sorted part is empty and the unsorted part is the entire list.

✓ The smallest element is selected from the unsorted array and swapped with
the leftmost element, and that element becomes a part of the sorted array.
This process continues moving unsorted array boundary by one element to
the right.

✓ This algorithm is not suitable for large data sets as its average and worst
case complexities are of Ο(n2), where n is the number of items.

Step by Step Process

The selection sort algorithm is performed using 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 other elements in the list.

Step 3: For every comparison, if any element is smaller than selected element (for
Ascending order), then these two are swapped.

Step 4: Repeat the same procedure with next position in the list till the entire list
is sorted.
// Selection sort program

#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]);

3.Insertion Sort

✓ Sorting is the process of arranging a list of elements in a particular order


(Ascending or Descending).

✓ Insertion sort algorithm arranges a list of elements in a particular order.

✓ In insertion sort algorithm, every iteration moves an element from unsorted


portion to sorted portion until all the elements are sorted in the list.

Step by Step Process

The insertion sort algorithm is performed using following steps...

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

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

Step 3: Repeat the above process until all the elements from the unsorted list are
moved into the sorted list.
// implementation of insertion 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]);

//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]);

}
OUTPUT INSERTION SORT:

Enter the size of the list: 8

Enter 8 integer values: 15 20 10 30 50 18 5 45

List after Sorting is: 5 10 15 18 20 30 45 50

4.QUICK SORT

✓ Quicksort is a simple sorting algorithm using the divide-and-conquer


recursive procedure.

✓ Quick sort is a highly efficient sorting 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 partitions an array and then calls itself recursively twice to sort
the two resulting subarrays.

✓ This algorithm is quite efficient for large-sized data sets as its average and
worst case complexity are of Ο(n2), where n is the number of items.

✓ The pivot value divides the list into two parts. And recursively, we find the
pivot for each sub-lists until all lists contains only one element.

Quick Sort Algorithm

Using pivot algorithm recursively, we end up with smaller possible partitions.


Each partition is then processed for quick sort. We define recursive algorithm for
quicksort as follows −

Step 1 − Make the right-most index value pivot


Step 2 − partition the array using pivot value

Step 3 − quicksort left partition recursively

Step 4 − quicksort right partition recursively

//quick sort implementation using c


#include<stdio.h>
int quciksort(int[],int,int);
int partition(int[],int,int);
int main()
{
int a[100],i,j,p,key,z;
int n;
printf("enter the size of array");
scanf("%d",&n);
printf("Enter %d elements into array\n",n);
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
printf("\n the array elements are \n");
for(i=0;i<n;i++)
{
printf(" %d",a[i]);
}
quicksort(a,0,n-1);
printf("\n the array elements in sorting are \n");
for(i=0;i<n;i++)
{
printf(" %d",a[i]);
}
}
int quicksort(int a[],int p,int n)
{
int q;
if(p<n)
{
q = partition(a,p,n);
quicksort(a,p,q-1);
quicksort(a,q+1,n);
}
}
int partition(int a[],int p,int n)
{
int pivot,j,i,temp;
pivot=a[n];
i=p-1;
for(j=p;j<n;j++)
{
if(a[j]<=pivot)
{
i++;
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}
temp=a[i+1];
a[i+1]=a[n];
a[n]=temp;
return i+1;
}
OUTPUT QUICK SORT:

enter the size of array10

Enter 10 elements into array

35 33 42 10 14 19 27 44 26 31

the array elements are

35 33 42 10 14 19 27 44 26 31

the array elements in sorting are

10 14 19 26 27 31 33 35 42 44

5. MERGE SORT

✓ Merge sort is a sorting technique based on divide and conquer technique.


With worst-case time complexity being Ο(n log n), it is one of the most
respected algorithms.

✓ Merge sort first divides the array into equal halves and then combines them
in a sorted manner.

To understand merge sort, we take an unsorted array as the following −

We know that merge sort first divides the whole array iteratively into equal
halves unless the atomic values are achieved. We see here that an array of 8
items is divided into two arrays of size 4.
This does not change the sequence of appearance of items in the original.
Now we divide these two arrays into halves.

We further divide these arrays and we achieve atomic value which can no more be
divided.

Now, we combine them in exactly the same manner as they were broken
down. Please note the color codes given to these lists.

We first compare the element for each list and then combine them into
another list in a sorted manner. We see that 14 and 33 are in sorted positions.
We compare 27 and 10 and in the target list of 2 values we put 10 first,
followed by 27. We change the order of 19 and 35 whereas 42 and 44 are
placed sequentially.

In the next iteration of the combining phase, we compare lists of two data
values, and merge them into a list of found data values placing all in a sorted
order.

After the final merging, the list should look like this –

Algorithm
Merge sort keeps on dividing the list into equal halves until it can no more be
divided. By definition, if it is only one element in the list, it is sorted. Then,
merge sort combines the smaller sorted lists keeping the new list sorted too.
Step 1 − if it is only one element in the list it is already sorted, return.
Step 2 − divide the list recursively into two halves until it can no more be divided.
Step 3 − merge the smaller lists into new list in sorted order.

// c program to implement merge sort

#include<stdio.h>

void mergesort(int a[],int i,int j);

void merge(int a[],int i1,int j1,int i2,int j2);

int main()

int a[30],n,i;

printf("Enter no of elements:");

scanf("%d",&n);

printf("Enter array elements:");

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

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

mergesort(a,0,n-1);

printf("\nSorted array is :");

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

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

return 0;

void mergesort(int a[],int i,int j)

int mid;

if(i<j)

mid=(i+j)/2;

mergesort(a,i,mid); //left recursion


mergesort(a,mid+1,j); //right recursion

merge(a,i,mid,mid+1,j); //merging of two sorted sub-arrays

void merge(int a[],int i1,int j1,int i2,int j2)

int temp[50]; //array used for merging


int i,j,k;
i=i1; //beginning of the first list
j=i2; //beginning of the second list
k=0;
while(i<=j1 && j<=j2) //while elements in both lists
{
if(a[i]<a[j])
temp[k++]=a[i++];
else
temp[k++]=a[j++];
}

while(i<=j1) //copy remaining elements of the first list

temp[k++]=a[I++];

while(j<=j2) //copy remaining elements of the second list

temp[k++]=a[j++];

//Transfer elements from temp[] back to a[]

for(i=i1,j=0;i<=j2;i++,j++)

a[i]=temp[j];

OUTPUT MERGE SORT:

Enter no of elements:8

Enter array elements:14 33 27 10 35 19 42 44

Sorted array is :10 14 19 27 33 35 42 44

You might also like