Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
7 views35 pages

Unit-3 (Sorting Searching) Notes1

The document provides an overview of sorting and searching techniques, focusing on selection sort, quick sort, and insertion sort using arrays. It explains the differences between internal and external sorting, outlines the algorithms for selection and insertion sorts, and compares their efficiencies. Additionally, the document includes C programming examples for both sorting methods and discusses the advantages and disadvantages of quick sort.

Uploaded by

gollaguna369
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)
7 views35 pages

Unit-3 (Sorting Searching) Notes1

The document provides an overview of sorting and searching techniques, focusing on selection sort, quick sort, and insertion sort using arrays. It explains the differences between internal and external sorting, outlines the algorithms for selection and insertion sorts, and compares their efficiencies. Additionally, the document includes C programming examples for both sorting methods and discusses the advantages and disadvantages of quick sort.

Uploaded by

gollaguna369
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/ 35

UNIT-III

Syllabus:
Sorting Selection sort, Quick Sort, Insertion sort techniques (Using Arrays)
Searching - Linear search, Binary search techniques (Using Arrays)

Sorting is the process of arranging elements either in ascending (or) descending order.

For example:
If we need to search for, particular record in database, roll numbers in a list, a number in a
telephone directory, a specific page in a book etc.
 If the data was kept in an unordered and unsorted form, it becomes difficult to search a
particular thing. But fortunately, the concept of sorting came into existence, making it easier
for everyone to arrange data in an order.
 Sorting arranges data in a sequence which makes searching easier.

Sorting can be classified into 2 types


1) Internal sorting
2) External sorting

1. Internal sorting:
 This method uses only the primary memory during sorting process.
 All data items are held in main memory and no secondary memory is required in the sorting..
 If all the data that is to be sorted can be accommodated at a time in memory is called Internal
Sorting.
Limitations:
• They can only process relatively small lists due to memory constraints.
3 types of internal sorts
1) Selection Sort
Ex:- selection sort , Heap sort
2) Insertion sort :
Ex: Insertion sort, Shell sort
3) Exchange Sort
Ex: Quick sort

External Sort:
Sorting large amount of data requires external or secondary memory. This process uses
external memory such as hard disk to store the data which does not fit in main memory so,
primary memory holds the current being sorted data only.
 All the external sorts are based on process of merging.
 Different parts of data are sorted separately and merged together

The criteria to judge which algorithm is better than the other is as follows −

 Time taken to sort the given data.


 Memory Space required to do so.
Selection sort:
Selection sort is another algorithm that is used for sorting. This sorting algorithm, iterates through the array
and finds the smallest number in the array and swaps it with the first element if it is smaller than the first
element. Next, it goes on to the second element and so on until all elements are sorted.

Algorithm for Selection Sort:

Step 1 − Set min to the first location


Step 2 − Search the minimum element in the array
Step 3 – swap the first location with the minimum value in the array
Step 4 – assign the second element as min.
Step 5 − Repeat the process until we get a sorted array.

Difference between Bubble Sort and Selection Sort

Bubble sort Selection sort


In bubble sort, two adjacent elements are In selection sort, the minimum element isselected
compared. If the adjacent elements are not atthe from the array and swap with anelement which is at
correct position, swapping would be the beginning of the
performed. unsorted sub array.
The time complexities in best case and worst The time complexity in both best and worst
case are O(n) and O(n2) respectively. cases is O(n 2).
It is not an efficient sorting technique. It is an efficient sorting technique as compared
to Bubble sort.
It uses an exchanging method. It uses a selection method.
It is slower than the selection sort as a greater It is faster than the bubble sort as a lesser
number of comparisons is required. number of comparisons is required.

Example:1
Example:2

As we can observe in the above array that it contains 6 elements. The above array is an unsorted array
whose indexing starts from 0 and ends at 5. The following are the steps used to sort the array:

Step 1: In the above array, the minimum element is 1; swap element 1 with an element 7.
Now, the sorted array contains only one element, i.e., 1, while the unsorted array contains 5
elements, i.e., 4, 10, 8, 3, 7.

Step 2: In the unsorted sub-array, the minimum element is 3, so swap element 3 with an element 4, which
is at the beginning of the unsorted sub-array.

Now the sorted array contains two elements, i.e., 1 and 3, while the unsorted array has four elements, i.e.,
10, 8, 4, 7, as shown in the above figure.

Step 3: Search the minimum element in the unsorted sub-array, and the minimum element is 4. Swap the
element 4 with an element 10, which is at the beginning of the unsorted sub- array.

Now, the sorted array contains three elements, i.e., 1, 3, 4, while the unsorted array has three elements,
i.e., 10, 8, 7

Step 4: Search the minimum element in the unsorted array, and the minimum element is 7. Swap element
7 with an element 10, which is at the beginning of the unsorted sub-array.

Now, the sorted array contains four elements, i.e., 1, 3, 4, 7, while the unsorted array has two elements,
i.e., 10, 8.
Step 5: Search the minimum element in the unsorted array and the minimum element is 8. Swap the
element 8 with an element 10 which is at the beginning of the unsorted sub-array.

Now, the sorted array contains the elements, i.e., 1, 3, 4, 7, 8.

Step 6: The last element is left in the unsorted sub-array. Move the last element to the sorted sub array
shown as below:

Selection sort program in C:

#include<stdio.h>
void read(int a[],int n);
void print(int a[],int n);
void selection_sort(int a[],int n);

void read(int a[],int n)


{
int i;
printf("enter %d elements\n",n);
for(i=0;i<n;i++)
scanf("%d",&a[i]);
}
void print(int a[],int n)
{
int i;
printf("Array elements are\n");
for(i=0;i<n;i++)
printf("%d ",a[i]);
printf("\n");
}
void selection_sort(int a[],int n)
{
int i,j,min,temp;
for(i=0;i<n-1;i++)
{
min=i;
for(j=i+1;j<n;j++)
{
if(a[min]>a[j])
{
min=j;
}
}
if(i!=min)
{
temp=a[i];
a[i]=a[min];
a[min]=temp;
}
}
}

int main( )
{
int a[20],n;

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


scanf("%d",&n);
read(a,n);
printf("Before Sorting\n");
print(a,n);
selection_sort(a,n);
printf("After Sorting\n");
print(a,n);
return 0;
}

Output:
enter number of elements
5
enter 5 elements
3
2
1
5
6
Before Sorting
Array elements are
32156
After Sorting
Array elements are
12356

Insertion Sort
Insertion sort works similar to the sorting of playing cards in hands. It is assumed that the first card is already sorted
in the card game, and then we select an unsorted card. If the selected unsorted card is greater than the first card, it will
be placed at the right side; otherwise, it will be placed at the left side. Similarly, all unsorted cards are taken and put
in their exact place.
Insertion sort in c is the simple sorting algorithm that virtually splits the given array into sorted and unsorted parts, then the
values from the unsorted parts are picked and placed at the correct position in the sorted part.

Insertion Sort Algorithm:

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.

Example:1

Example:2
Example:3

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.


Example:4

C program to sort the elements using Insertion sort.


#include<stdio.h>
void read(int a[],int n);
void print(int a[],int n);
void insertion_sort(int a[],int n);

void read(int a[],int n)


{
int i;
printf("enter %d elements\n",n);
for(i=0;i<n;i++)
scanf("%d",&a[i]);
}
void print(int a[],int n)
{
int i;
printf("Array elements are\n");
for(i=0;i<n;i++)
printf("%d ",a[i]);
printf("\n");
}
void insertion_sort(int a[],int n)
{
int i,j,key;
for (i = 1 ; i < n ; i++)
{
key=a[i];
j = i-1;
while ( j >= 0 && a[j] > key)
{
a[j+1] = a[j];
j--;
}
a[j+1]=key;
}
}
int main( )
{
int a[20],n;

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


scanf("%d",&n);
read(a,n);
printf("Before Sorting\n");
print(a,n);
insertion_sort(a,n);
printf("After Sorting\n");
print(a,n);
return 0;
}

Output:
enter number of elements
5
enter 5 elements
4
3
2
1
7
Before Sorting
Array elements are
43217
After Sorting
Array elements are
12347
Difference between selection sort and Insertion sort

Selection Sort Insertion Sort

Selection sort sorts by identifying the smallest element Insertion sort sorts by interchanging one element at a
from the unsorted group and selecting it to interchange time from the sorted group with the partially sorted
it with the elements from the sorted group and puts in group.
the correct location.

Selection sorts first finds the smallest element from the Transfers one element at a time to the sorted group of
unsorted group and then transfers it accordingly. the elements.

Selection sort is less efficient than insertion sort. Insertion sort is more efficient than selection sort.

Selection sort is very much simpler as compared to Insertion sort is more complex than selection sort.
insertion sort as the process of finding smaller numbers
from a group of numbers is very easier.

Selection sorting is an unstable way of sorting elements Insertion sort is a very stable sorting algorithm if
of an array if compared to insertion sorting. compared to selection sort.

In selection sorting, no best case time complexity is O(N) is the best case time complexity in insertion
available. O (N2) is the only time complexity available sorting when the array has to be in ascending order.
for all cases.

While doing selection sorting, the number of swapping While doing sorting through insertion sorting, the
operations performed is less than the number of number of swapping operations performed is higher
comparisons done. than the comparison operation performed.

In insertion sorting, the element to be sorted is known


In selection sorting, the location of the sorted element beforehand and the correct position for placing the
is known by the algorithm but the element which has to element is searched by the algorithm.
be placed at the location is searched by the algorithm.

In selection sorting, immediate data cannot be dealt The major benefit of insertion sorting is that immediate
with as the data is needed to be present at the very data can also be dealt with by this way of sorting as this
beginning of the sorting process. technique is done live.

Quick Sort:

It is a faster and highly efficient sorting algorithm. 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 -
 Pivot can be random, i.e. select the random pivot from the given array.
 Pivot can either be the rightmost element of the leftmost element of the given array.
 Select median as the pivot element.

Quick sort is based on partition. It is also known as partition exchange sorting. The basic concept of
quick sort process is pick one element from an array and rearranges the remaining elements around
it.This element divides the main list into two sub lists. This chosen element is called pivot. Once pivot
is chosen, then it shifts all the elements less than pivot to left of value pivot and all the elements greater
than pivot are shifted to the right side. This procedure of choosing pivot and partition the list is
applied recursively until sub-lists consisting of only one element.

Advantages of quick sort:


This is faster sorting method among all.
2. Its efficiency is also relatively good.
3. It requires relatively small amount of memory.

Disadvantages of quick sort:


1. It is complex method of sorting so, it is little hard to implement than other sorting methods.

Quick sort algorithm:


Step 1 - Consider the first element of the list as pivot (i.e., Element at first position in the list).
Step 2 - Define two variables i and j. Set i and j to first and last elements of the list respectively.
Step 3 - Increment i until list[i] > pivot then stop.
Step 4 - Decrement j until list[j] < pivot then stop.
Step 5 - If i < j then exchange list[i] and list[j].
Step 6 - Repeat steps 3,4 & 5 until i > j.
Step 7 - Exchange the pivot element with list[j] element.
Pseudo Code:
QUICKSORT (arrayA, low,high)
{
if (low < high)
{
p = partition(arrayA, low, high)
QUICKSORT (arrayA, low, p - 1)
QUICKSORT (arrayA, p + 1, high)
}
}
Algorithm partition (arrayA,low,high)
{
pivot=A[low]
i=low,j=high
while(i<=j)
{
while(A[i]<=pivot)
i++
while(A[j]=>pivot)
j—
if(i<=j) then
swap(A[i],A[j])
}
If(i>j)
swap(A[j],pivot)
}

C program to sort the elements using Quick sort.

#include<stdio.h>
void read(int a[],int n);
void print(int a[],int n);
void quicksort(int a[25],int first,int last);

void read(int a[],int n)


{
int i;
printf("enter %d elements\n",n);
for(i=0;i<n;i++)
scanf("%d",&a[i]);
}
void print(int a[],int n)
{
int i;
printf("Array elements are\n");
for(i=0;i<n;i++)
printf("%d ",a[i]);
printf("\n");
}
void quicksort(int a[25],int first,int last)
{
int i, j, pivot, temp;
if(first<last)
{
pivot=first;
i=first;
j=last;
while(i<j)
{
while(a[i]<=a[pivot]&&i<last)
i++;
while(a[j]>a[pivot])
j--;
if(i<j)
{
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}
temp=a[pivot];
a[pivot]=a[j];
a[j]=temp;
quicksort(a,first,j-1);
quicksort(a,j+1,last);
}
}
int main()
{
int i, n, a[25];
printf("How many elements are u going to enter?: ");
scanf("%d",&n);
read(a,n);
printf("Before Sorting\n");
print(a,n);
quicksort(a,0,n-1);
printf("After Sorting\n");
print(a,n);

return 0;
}

INPUT:
How many elements are u going to enter?: 5
Enter 5 elements: 5 4 3 2 1
OUTPUT:
elements of an array before sorting: 5 4 3 2 1
Order of Sorted elements: 1 2 3 4 5

ADVANTAGES AND DISADVANTAGES OF SORTING ALGORITHMS


What is Time and Space Complexity?

Time complexity is the amount of time taken to run an algorithm. It is the measure of the number of elementary
operations performed by an algorithm and an estimate of the time required for that operation. It also depends on
external factors such as the compiler, the processor’s speed, etc.

Space complexity is the amount of memory space an algorithm/program uses during its entire execution. It measures
the number of variables created to store values, including both the inputs and the outputs .

TIME AND SPACE COMPLEXITY OF SORTING ALGORITHMS


Searching
Searching in C Language has to check for an element or retrieve an element from any data structure where the
data is stored. Based on the type of search operation, there are generally two algorithms defined in C:
1. Linear Search or Sequential Search
2. Binary Search
Difference between Searching and Sorting Algorithm:

S.No Searching Algorithm Sorting Algorithm

1 Searching algorithms are designed to find and Sorting algorithms are used to organize a list of
retrieve data elements from a data structure. data or an array in a specific order.
2 Searching algorithms are generally divided into Sorting algorithms can be classified into two
two categories – Interval Search and Sequential types- Internal Sorting and External Sorting.
Search.

3 The Linear Search and the Binary Search are the The Bubble Sort, Insertion Sort, Selection Sort,
examples of Searching Algorithms. Merge Sort, Quick Sort etc are the examples of
Sorting Algorithms.

1. Sequential Search

 Sequential search is also called as Linear Search.


 Sequential search starts at the beginning of the list and checks every element of the list.
 It is a basic and simple search algorithm.
 Sequential search compares the element with all the other elements given in the list. If theelement is
matched, it returns the value index, else it returns -1.

Working of Linear search:

Now, let's see the working of the linear search Algorithm.


To understand the working of linear search algorithm, let's take an unsorted array. It will be easy to understand the
working of linear search with an example.
Let the elements of array are -

Let the element to be searched is K = 41


Now, start from the first element and compare K with each element of the array.
The value of K, i.e., 41, is not matched with the first element of the array. So, move to the next element. And follow
the same process until the respective element is found.

Now, the element to be searched is found. So algorithm will return the index of the element matched.

Linear SearchAlgorithm
LinearSearch(array, key)
for each itemin the array
if item == value
return its index
Program for Linear Search(Sequential Search)

#include <stdio.h>
int main()
{
int num;

int array[50],i, key, flag = 0;

printf("Enter size of array:");


scanf("%d",&num);
printf("Enter the elements one by one \n");
for (i = 0; i < num; i++)
{
scanf("%d", &array[i]);
}

printf("Enter the element to be searched ");


scanf("%d", &key);

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


{
if (key == array[i] )
{
flag = 1;
break;
}
}

if (flag == 1)
printf("Element is present in the array at position %d",i+1);
else
printf("Element is not present in the array\n");
return 0;
}
OUTPUT:
Enter size of array:5
Enter the elements one by one
5
3
6
2
1
Enter the element to be searched 6
Element is present in the array at position 3
Linear Search Program Using Functions:

#include<stdio.h>
void read(int a[],int n)
{
int i;
printf("enter %d elements\n",n);
for(i=0;i<n;i++)
scanf("%d",&a[i]);
}
void print(int a[],int n)
{
int i;
printf("Array elements are\n");
for(i=0;i<n;i++)
printf("%d ",a[i]);
printf("\n");
}

int linear_search(int a[],int n,int key)


{
int i;
for(i=0;i<n;i++)
{
if(a[i]==key)
return i;
}
return -1;
}

int main(void)
{
int a[20],n,key,pos;
printf("enter number of elements\n");
scanf("%d",&n);
read(a,n);
printf("enter key\n");
scanf("%d",&key);
pos=linear_search(a,n,key);
if(pos!=-1)
printf("%d found at position %d\n",key,pos+1);
else
printf("%d not found\n",key);
return 0;
}

OUTPUT:
enter number of elements
5
enter 5 elements
2
3
6
3
7
enter key
3
3 found at position 1

Program:
Write a C program to search a string in a list of strings using linear search. If the string is found display the
position, otherwise print “string not present”.

#include<stdio.h>
#include<string.h>
int main()
{
char str[20][50], s1[50];
int n, i, found=0;

printf("Enter how many string (names): ");


scanf("%d", &n);

printf("Enter %d strings:\n", n);


for(i=0; i<n; i++)
{
scanf("%s", str[i]);
}

printf("Enter a string to search: ");


scanf("%s", s1);
for(i=0; i<n; i++)
{
if(strcmp(s1, str[i]) == 0)
{
found=1;
break;
}
}
if(found==1)
printf("found at position -%d\n", i+1);
else
printf("Not found");
return 0;
}
Input:
Enter how many string (names): 5
Enter 5 strings: kohli sachin rahul rohith dhoni
Enter a string to search: rahul
OUTPUT:
found at position -3
2. Binary Search
 Binary Search is used for searching an element in a sorted array.
 It is a fast search algorithm with run-time complexity of O(log n).
 Binary search works on the principle of divide and conquer.
 This searching technique looks for a particular element by comparing the middle most element ofthe collection.
 It is useful when there are large number of elements in an array.

Working of Binary search


Now, let's see the working of the Binary Search Algorithm.
To understand the working of the Binary search algorithm, let's take a sorted array. It will be easy to understand the working of
Binary search with an example.
There are two methods to implement the binary search algorithm –
Iterative method
Recursive method
The recursive method of binary search follows the divide and conquer approach.Let the elements of array are –

Let the element to search is, K = 56

We have to use the below formula to calculate the mid of the array -mid = (beg + end)/2
So, in the given array -
beg = 0
end = 8
mid = (0 + 8)/2 = 4. So, 4 is the mid of the array.
Now, the element to search is found. So algorithm will return the index of the element matched.

Binary Search Algorithm

Iteration Method
while low <= high: (do until the pointers low and high meet each other.
mid = (low + high)/2
if (x == arr[mid])
return mid
else if (x > arr[mid])
low = mid + 1
else(x < arr[mid])
high = mid - 1

Recursive Method
binarySearch(arr, x, low, high)
if low > high
return False
else
mid = (low + high) / 2
if x == arr[mid]
return mid
else if x > arr[mid]
return binarySearch(arr, x, mid + 1, high)
else
return binarySearch(arr, x, low, mid – 1)
Binary search in C using recursion
#include <stdio.h>
void binary_search(int [], int, int, int);
void bubble_sort(int [], int);
int main()
{
int key, n, i;
int list[25];
printf("Enter size of a list: ");
scanf("%d", &size);
printf("Enter elements\n");
for(i = 0; i < sn; i++)
{
scanf("%d",&list[i]);
}
bubble_sort(list, n);
printf("\n");
printf("Enter key to search\n");
scanf("%d", &key);
binary_search(list, 0, size, key);
}
void bubble_sort(int list[], int n)
{
int temp, i, j;
for (i = 0; i < n; i++)
{
for (j = i; j < n; j++)
{
if (list[i] > list[j])
{
temp = list[i];
list[i] = list[j];
list[j] = temp;
}
}
}
}
void binary_search(int list[], int lo, int hi, int key)
{
int mid;
if (lo > hi)
{
printf("Key not found\n");
return;
}
mid = (lo + hi) / 2;
if (list[mid] == key)
{
printf("Key found\n");
}
else if (list[mid] > key)
{
binary_search(list, lo, mid - 1, key);
}
else if (list[mid] < key)
{
binary_search(list, mid + 1, hi, key);
}
}

Binary search program(USING Iteration Method)

#include<stdio.h>

int main()
{
int arr[50],i,n,x,flag=0,first,last,mid;

printf("Enter size of array:");


scanf("%d",&n);
printf("\nEnter array element(ascending order)\n");

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

printf("\nEnter the element to search:");


scanf("%d",&x);

first=0;
last=n-1;

while(first<=last)
{
mid=(first+last)/2;

if(x==arr[mid])
{
flag=1;
break;
}
else if(x>arr[mid])
first=mid+1;
else
last=mid-1;
}

if(flag==1)
printf("\nElement found at position %d",mid+1);
else
printf("\nElement not found");

return 0;
}

OUTPUT:
Enter size of array:5
Enter array element(ascending order)
10
20
30
40
50
Enter the element to search:30

Element found at position 3

1. Time Complexity:

Case Time Complexity

Best Case O(1)

Average Case O(logn)

Worst Case O(logn)

Space Complexity O(1)


Differences between Linear search and Binary search

linear search Binary search

Definition The linear search starts searching from the It finds the position of the searched element
first element and compares each element with by finding the middle element of the array.
a searched element till the element is not
found.

Sorted data In a linear search, the elements don't need to The pre-condition for the binary search is
be arranged in sorted order. that the elements must be arranged in a
sorted order.

Implementation The linear search can be implemented on any The implementation of binary search is
linear data structure such as an array, linked limited as it can be implemented only on
list, etc. those data structures that have two-way
traversal.

Approach It is based on the sequential approach. It is based on the divide and conquer
approach.

Size It is preferrable for the small-sized data sets. It is preferrable for the large-size data sets.

Efficiency It is less efficient in the case of large-size data It is more efficient in the case of large-size
sets. data sets.

Worst-case In a linear search, the worst- case scenario for In a binary search, the worst-case scenario
scenario finding the element is O(n). for finding the element is O(log2n).

Best-case In a linear search, the best-case scenario for In a binary search, the best-case scenario for
scenario finding the first element in the list is O(1). finding the first element in the list is O(1).

Dimensional It can be implemented on both a single and It can be implemented only on a


array multidimensional array. multidimensional array.

Short Answer Questions


1. Define sorting
2. What is meant by Sorting and searching?
3. What are the types of sorting available in C?
4. Define Bubble sort.
5. Define insertion sort?
6. Define selection sort?
7. What is the purpose of quick sort and advantage?
8. Advantage of quick sort?
9. What do you mean by internal and external sorting?
10. Define searching
11. What is meant by linear search?
12. What is binary search?
13. Differentiate linear search and binary search?
14. What is time and space complexity?
15. Time and space complexity of sorting algorithms
Long Answer Questions:

1. Explain in detail about sorting and different types of sorting techniques


2. Write a C-program for sorting integers in ascending order using insertion sort
3. Explain the algorithm for insertion sort and give a suitable example.
4. Demonstrate the insertion sort results for each insertion for the following initial array of elements . 25 6 15 12 8 34 9 18 2
5. Demonstrate the selection sort results for each pass for the following initial array of elements . 21 6 3 57 13 9 14 18 2
6. Write a program to explain selection sort. Which type of technique does it belong.
7. Explain the algorithm for selection sort and give a suitable example.
8. Show the quick sort results for each exchange for the following initial array of elements 35 54 12 18 23 15 45 38
9. Explain the algorithm for QUICK sort ( partition exchange sort) and give a suitable example.
10. Write a program to implement Quick sort.
11. Explain a sorting technique which follows divide and conquer mechanism with an example.
12. Write and explain linear search procedure or algorithm with a suitable example.
13. Write a C program that searches a value in a stored array using linear search.
14. Write a program for recursive binary search to find the given element within array. For What data binary search is not
applicable?
15. Write a C program that searches a value in a stored array using non recursive binary search.
QUICK SORT EXAMPLE:
pivot

50 30 10 90 80 20 40 70
i j

50<=50 True i++

pivot

50 30 10 90 80 20 40 70
i j

30<=50 True i++

pivot

50 30 10 90 80 20 40 70
i j

10<=50 True i++

pivot

50 30 10 90 80 20 40 70
i j

90<=50 False stop

pivot

50 30 10 90 80 20 40 70
i j

70 =>50 True j--

pivot

50 30 10 90 80 20 40 70
i j

40=>50 False stop


pivot

50 30 10 90 80 20 40 70
i j

i<=j (3<=6) True swap (list [i],list[j])

pivot

50 30 10 40 80 20 90 70
i j

40<=50 True i++

pivot

50 30 10 40 80 20 90 70
i j

80<=50 False Stop

pivot

50 30 10 40 80 20 90 70
i j

90=>50 True j - -

pivot

50 30 10 40 80 20 90 70
i j

20=>50 False stop

pivot

50 30 10 40 80 20 90 70
i j

i<=j ( 4 <=5) True swap(list[i],list[j])


pivot

50 30 10 40 20 80 90 70
i j

20<=50 True i++

pivot

50 30 10 40 20 80 90 70
i j

80<=50 False stop

pivot

50 30 10 40 20 80 90 70
i j

80 => 50 True j—

pivot

50 30 10 40 20 80 90 70
j i

20 = >50 False stop

pivot

50 30 10 40 20 80 90 70
j i

i<=j 5<=4 False stop

pivot

50 30 10 40 20 80 90 70
j i

if(i>j) 5 >4 True swap(list[j] ,pivot)


pivot

20 30 10 40 50 80 90 70
j i

Now, the element on the right side and left side are greater than and smaller
than 50 respectively.

Now we get two sorted lists:

Sublist1 Sublist1

20 30 10 40 80 90 70

pivot

20 30 10 40
i j

20<=20 True i++

pivot

20 30 10 40
i j

30<=20 false STOP

pivot

20 30 10 40
i j

40=>20 True j- -

pivot

20 30 10 40
i j

10 => 20 False STOP


pivot
20 30 10 40
i j

i<=j 0 <=2 True swap(list[i],list[j])

pivot
20 10 30 40
i j

10<=20 True i++

pivot
20 10 30 40
i j

30<=20 false

pivot
20 10 30 40
i j

30 =>20 True j--

pivot
20 10 30 40
j i

10>= 20 False stop

pivot
20 10 30 40
j i

i<=j 2 <=1 false stop

pivot
20 10 30 40
j i

if(i>j) 5>4 True swap( list[j],pivot)

pivot
10 20 30 40
j i
Sublist2
pivot
80 90 70
i j

80<=80 True i++

pivot
80 90 70
i j

90<=80 false stop

pivot
80 90 70
i j

70>=80 false stop

pivot
80 90 70
i j

i<=j 1<=2 swap(list[i] ,list[j])

pivot
80 70 90
i j

70<=80 true i++

80 70 90
i j

90<=80 true i++ stop

80 70 90
i j

90=>80 true j- -

80 70 90
j i
70=>80 false stop

80 70 90
j i

i<=j 2<= 1 false stop

80 70 90
j i

if( i>j) true swap(list[j], pivot)

70 80 90

You might also like