Notes
Notes
Notes
3 0 0 3
COURSE OBJECTIVES:
• To introduce the basics of C programming language.
• To learn the concepts of advanced features of C.
• To understand the concepts of ADTs and linear data structures.
• To know the concepts of non-linear data structure and hashing.
• To familiarize the concepts of sorting and searching techniques.
5.2.1 Algorithm:
Step 1 − If the element is the first one, it is already sorted.
Step 2 – Move to next element
Step 3 − Compare the current element with all elements in the sorted array
Step 4 – If the element in the sorted array is smaller than the current element, iterate to
the next element. Otherwise, shift all the greater element in the array by one
position towards right
Step 5 − Insert the value at the correct position
Step 6 − Repeat until the complete list is sorted
5.2.2 Working of Insertion sort Algorithm
Consider an unsorted array of elements 40, 10, 9, 20, 30, 50
➢ The above steps represents how insertion sort works. Insertion sort works like the
way we sort playing cards in our hands. It always starts with the second element
as key. The key is compared with the elements ahead of it and is put it in the right
place.
5.4 Sorting and Searching Techniques
➢ At the first step, 40 has nothing before it. Element 10 is compared to 40 and is
inserted before 40. Element 9 is smaller than 40 and 10, so it is inserted before 10
and this operation continues until the array is sorted in ascending order.
5.2.3 Analysis of Insertion Sort:
Time Complexity
Best O(n)
Worst O(n2)
Average O(n2)
Space Complexity O(1)
Stability Yes
5.2.4 Applications
➢ The insertion sort is used when:
• The array is has a small number of elements
• There are only a few elements left to be sorted
Example Program 5.1
#include <stdio.h>
int main()
{
int n, array[1000], c, d, t;
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]);
}
for (c = 1 ; c <= n - 1; c++)
{
C Programming and Data Structures 5.5
d = c;
while ( d > 0 && array[d] < array[d-1])
{
t = array[d];
array[d] = array[d-1];
array[d-1] = t;
d--;
}
}
printf("Sorted list in ascending order:\n");
for (c = 0; c <= n - 1; c++)
{
printf("%d\n", array[c]);
}
return 0;
}
Output
Enter the number of elements
5
Enter 5 integers
40
30
20
10
40
Sorted list in ascending order
10
20
30
5.6 Sorting and Searching Techniques
40
40
//Declaring variables
int array[100],n,i;
//Number of elements in array form user input
printf("Enter the number of element you want to Sort : ");
scanf("%d",&n);
//code to ask to enter elements from user equal to n
printf("Enter Elements in the list : ");
for(i = 0; i < n; i++)
{
scanf("%d",&array[i]);
}
//calling quickSort function defined above
quicksort(array,0,n-1);
//print sorted array
printf("Sorted elements: ");
for(i=0;i<n;i++)
printf(" %d",array[i]);
getch();
return 0;
}
Output
Enter the number of element you want to sort: 5
Enter the elements in the list:
7
10
3
21
15
Sorted elements: 3 7 10 15 21
C Programming and Data Structures 5.11
First, construct a heap from the given array and convert it into max heap
5.12 Sorting and Searching Techniques
After converting the given heap into max heap, the array elements are
➢ Next step is to delete the root element (89) from the max heap. To delete this node,
swap it with the last node, i.e. (11). After deleting the root element, again heapify
it to convert it into max heap.
➢ After swapping the array element 89 with 11, and converting the heap into max-
heap, the elements of array are
➢ In the next step, again delete the root element (81) from the max heap. To delete
this node, swap it with the last node, i.e. (54). After deleting the root element,
again heapify it to convert it into max heap.
C Programming and Data Structures 5.13
➢ After swapping the array element 81 with 54 and converting the heap into max-
heap, the elements of array are
➢ In the next step, delete the root element (76) from the max heap again. To delete
this node, swap it with the last node, i.e. (9). After deleting the root element, again
heapify it to convert it into max heap.
➢ After swapping the array element 76 with 9 and converting the heap into max-
heap, the elements of array are
➢ In the next step, again delete the root element (54) from the max heap. To delete
this node, swap it with the last node, i.e. (14). After deleting the root element,
again heapify it to convert it into max heap.
5.14 Sorting and Searching Techniques
➢ After swapping the array element 54 with 14 and converting the heap into max-
heap, the elements of array are
➢ In the next step, again delete the root element (22) from the max heap. To delete
this node, swap it with the last node, i.e. (11). After deleting the root element,
again heapify it to convert it into max heap.
➢ After swapping the array element 22 with 11 and converting the heap into max-
heap, the elements of array are
➢ In the next step, again delete the root element (14) from the max heap. To delete
this node, swap it with the last node, i.e. (9). After deleting the root element, again
heapify it to convert it into max heap.
C Programming and Data Structures 5.15
➢ After swapping the array element 14 with 9 and converting the heap into max-
heap, the elements of array are
➢ In the next step, again delete the root element (11) from the max heap. To delete
this node, swap it with the last node, i.e. (9). After deleting the root element, again
heapify it to convert it into max heap.
➢ After swapping the array element 11 with 9, the elements of array are
➢ Now, heap has only one element left. After deleting it, heap will be empty.
heapify(a, n, largest);
}
}
/*Function to implement the heap sort*/
void heapSort(int a[], int n)
{
for (int i = n / 2 - 1; i >= 0; i--)
heapify(a, n, i);
// One by one extract an element from heap
for (int i = n - 1; i >= 0; i--) {
/* Move current root element to end*/
// swap a[0] with a[i]
int temp = a[0];
a[0] = a[i];
a[i] = temp;
heapify(a, i, 0);
}
}
/* function to print the array elements */
5.18 Sorting and Searching Techniques
➢ Merge sort first divides the array into equal halves and then combines them in a
sorted manner
5.5.1 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.
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.
5.20 Sorting and Searching Techniques
Now, combine them in the same manner they were broken. 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
k++;
}
while (i<n1)
{
a[k] = LeftArray[i];
i++;
k++;
}
while (j<n2)
{
a[k] = RightArray[j];
j++;
k++;
}
}
void mergeSort(int a[], int beg, int end)
{
if (beg < end)
{
int mid = (beg + end) / 2;
mergeSort(a, beg, mid);
mergeSort(a, mid + 1, end);
merge(a, beg, mid, end);
}
}
/* Function to print the array */
void printArray(int a[], int n)
{
int i;
C Programming and Data Structures 5.23
5.7.2 Algorithm
Linear_Search(a, n, val) // 'a' is the given array, 'n' is the size of given array, 'val'
is the value to search
Step 1: set pos = -1
Step 2: set i = 1
Step 3: repeat step 4 while i <= n
Step 4: if a[i] == val
set pos = i
print pos
go to step 6
[end of if]
set ii = i + 1
[end of loop]
Step 5: if pos = -1
print "value is not present in the array "
[end of if]
Step 6: exit
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.
C Programming and Data Structures 5.27
Now, the element to be searched is found. So algorithm will return the index of
the element matched.
{
if (a[i] == val)
return i+1;
}
return -1;
}
int main() {
int a[] = {59, 40, 33, 11, 57, 41, 27, 18, 53}; // given array
int val = 41; // value to be searched
int n = sizeof(a) / sizeof(a[0]); // size of array
int res = linearSearch(a, n, val); // Store result
printf("The elements of the array are - ");
for (int i = 0; i < n; i++)
printf("%d ", a[i]);
printf("\nElement to be searched is - %d", val);
if (res == -1)
printf("\nElement is not present in the array");
else
printf("\nElement is present at %d position of array", res);
return 0;
}
Output
The elements of the array are - 59, 40, 33, 11, 57, 41, 27, 18, 53
Element to be searched is – 41
Element is present at 6 position of array
➢ Binary search follows the divide and conquer approach in which the list is divided
into two halves, and the item is compared with the middle element of the list.
➢ If the match is found then, the location of the middle element is returned.
➢ Otherwise, we search into either of the halves depending upon the result produced
through the match.
5.8.1 Algorithm
Binary_Search(a, lower_bound, upper_bound, val) // 'a' is the given array,
'lower_bound' is the index of the first array element, 'upper_bound' is the index of the last
array element, 'val' is the value to search
Step 1: set beg = lower_bound, end = upper_bound, pos = - 1
Step 2: repeat steps 3 and 4 while beg <=end
Step 3: set mid = (beg + end)/2
Step 4: if a[mid] = val
set pos = mid
print pos
go to step 6
else if a[mid] > val
set end = mid - 1
else
set beg = mid + 1
[end of if]
[end of loop]
Step 5: if pos = -1
print "value is not present in the array"
[end of if]
Step 6: exit
Now, the element to search is found. So algorithm will return the index of the
element matched.
5.8.3 Binary Search complexity:
Time Complexity
Best O(1)
Worst O(logn)
Average O(logn)
Space Complexity O(1)
int mid;
if(end >= beg)
{ mid = (beg + end)/2;
/* if the item to be searched is present at middle */
if(a[mid] == val)
{
return mid+1;
}
/* if the item to be searched is smaller than middle, then it can only be in
left subarray*/
else if(a[mid] < val)
{
return binarySearch(a, mid+1, end, val);
}
/* if the item to be searched is greater than middle, then it can only be in
right subarray*/
else
{
return binarySearch(a, beg, mid-1, val);
}
}
return -1;
}
int main() {
int a[] = {21, 14, 35, 30, 40, 51, 55, 57, 70}; // given array
int val = 40; // value to be searched
int n = sizeof(a) / sizeof(a[0]); // size of array
int res = binarySearch(a, 0, n-1, val); // Store result
printf("The elements of the array are - ");
C Programming and Data Structures 5.33
REVIEW QUESTIONS
PART A
1. What is sorting?
➢ Sorting refers to arranging data in a particular format. Sorting algorithm specifies
the way to arrange data in a particular order.
2. Define insertion sort?
➢ Successive element in the array to be sorted and inserted into its proper place
with respect to the other already sorted element. We start with second element
and put it in its correct place, so that the first and second elements of the array
are in order.
3. Write short notes on quick sort.
➢ Quicksort is a divide-and-conquer algorithm. It works by selecting a 'pivot'
element from the array and partitioning the other elements into two sub-arrays,
according to whether they are less than or greater than the pivot. For this reason,
it is sometimes called partition-exchange sort.
4. What is Time Complexity for Quick Sort?
12. Why quick sort is preferred for arrays and merge sort for linked lists?
➢ Quick sort is an in-place sorting algorithm, i.e. which means it does not require
any additional space, whereas Merge sort does, which can be rather costly. In
merge sort, the allocation and deallocation of the excess space increase the
execution time of the algorithm.
➢ Unlike arrays, in linked lists, we can insert elements in the middle in O(1) extra
space and O(1) time complexities if we are given a reference/pointer to the
previous node. As a result, we can implement the merge operation in the merge
sort without using any additional space.
13. In which case insertion sort is used?
➢ Insertion sort has a fast best-case running time and is a good sorting algorithm
to use if the input list is already mostly sorted.
5.36 Sorting and Searching Techniques
PART B