SlideShare a Scribd company logo
PROJECT ON- MODULE 1 (DSA)
FACULTY NAME – SACHIN AGARWAL
PRESENTED BY – ANUJ KUMAR
ROLL NO -2011008
REG NO. – 20030480006
BRANCH – INFORMATION TECHNOLOGY
COLLEGE NAME – BIT SINDRI
TOPICS COVERED
 INTRODUCTION TO DATA STRUCTURES
 ALGORITHMS AND ASYMPTOMATIC NOTATIONS
 ARRAY
 STACK
 LINKED LIST
INTRODUCTION TO DATA STRUCTURES
• Data Structure can be defined as the group of data elements which provides an efficient
way of storing and organising data in the computer so that it can be used efficiently.
Some examples of Data Structures are arrays, Linked List, Stack, Queue, etc. Data
Structures are widely used in almost every aspect of Computer Science i.e. Operating
System, Compiler Design, Artifical intelligence, Graphics and many more.
• Data Structures are the main part of many computer science algorithms as they enable
the programmers to handle the data in an efficient way. It plays a vital role in enhancing
the performance of a software or a program as the main function of the software is to
store and retrieve the user's data as fast as possible.
NEED OF DATA STRUCTURE
• As applications are getting complexed and amount of data is increasing day by day, there may arrise the
following problems:
• Processor speed: To handle very large amout of data, high speed processing is required, but as the data is
growing day by day to the billions of files per entity, processor may fail to deal with that much amount of
data.
• Data Search: Consider an inventory size of 106 items in a store, If our application needs to search for a
particular item, it needs to traverse 106 items every time, results in slowing down the search process.
• Multiple requests: If thousands of users are searching the data simultaneously on a web server, then there
are the chances that a very large server can be failed during that process
ADVANTAGES OF DATA STRUCTURES
• Advantages of Data Structures
• Efficiency: Efficiency of a program depends upon the choice of data structures. For example: suppose, we
have some data and we need to perform the search for a perticular record. In that case, if we organize our
data in an array, we will have to search sequentially element by element. hence, using array may not be
very efficient here. There are better data structures which can make the search process efficient like
ordered array, binary search tree or hash tables.
• Reusability: Data structures are reusable, i.e. once we have implemented a particular data structure, we
can use it at any other place. Implementation of data structures can be compiled into libraries which can be
used by different clients.
• Abstraction: Data structure is specified by the ADT which provides a level of abstraction. The client
program uses the data structure through interface only, without getting into the implementation details.
CLASSIFICATION OF DATA SRUCTURES
 Linear Data Structures: A data structure is called linear if all of its elements are arranged in the linear order.
In linear data structures, the elements are stored in non-hierarchical way where each element has the
successors and predecessors except the first and last element.
 Types of Linear Data Structures are given below:
 Arrays: An array is a collection of similar type of data items and each data item is called an element of the
array. The data type of the element may be any valid data type like char, int, float or double.
The elements of array share the same variable name but each one carries a different index number known as
subscript. The array can be one dimensional, two dimensional or multidimensional.
The individual elements of the array age are:
age[0], age[1], age[2], age[3],......... age[98], age[99].
 Linked List: Linked list is a linear data structure which is used to maintain a list in the memory. It can be
seen as the collection of nodes stored at non-contiguous memory locations. Each node of the list contains a
pointer to its adjacent node.
 Stack: Stack is a linear list in which insertion and deletions are allowed only at one end, called top.
 A stack is an abstract data type (ADT), can be implemented in most of the programming languages. It is
named as stack because it behaves like a real-world stack, for example: - piles of plates or deck of cards
etc.
 Queue: Queue is a linear list in which elements can be inserted only at one end called rear and deleted only
at the other end called front.
LINEAR DATA STRUCTURES
Non Linear Data Structures: This data structure does not form a sequence i.e. each item or element is
connected with two or more other items in a non-linear arrangement. The data elements are not arranged in
sequential structure.
NON LINEAR DATA STRUCTURES
Types of Non Linear Data Structures are given below:
Trees: Trees are multilevel data structures with a hierarchical relationship among its elements known as nodes.
The bottommost nodes in the herierchy are called leaf node while the topmost node is called root node. Each
node contains pointers to point adjacent nodes.
Tree data structure is based on the parent-child relationship among the nodes. Each node in the tree can have
more than one children except the leaf nodes whereas each node can have atmost one parent except the root
node. Trees can be classfied into many categories which will be discussed later in this tutorial.
Graphs: Graphs can be defined as the pictorial representation of the set of elements (represented by vertices)
connected by the links known as edges. A graph is different from tree in the sense that a graph can have cycle
while the tree can not have the one.
OPERATIONS ON DATA STRUCTURE
1) Traversing: Every data structure contains the set of data elements. Traversing the data structure
means visiting each element of the data structure in order to perform some specific operation like
searching or sorting.
Example: If we need to calculate the average of the marks obtained by a student in 6 different subject,
we need to traverse the complete array of marks and calculate the total sum, then we will devide that
sum by the number of subjects i.e. 6, in order to find the average.
2) Insertion: Insertion can be defined as the process of adding the elements to the data structure at
any location.
If the size of data structure is n then we can only insert n-1 data elements into it.
3) Deletion:The process of removing an element from the data structure is called Deletion. We can delete
an element from the data structure at any random location.
If we try to delete an element from an empty data structure then underflow occurs.
4) Searching: The process of finding the location of an element within the data structure is called Searching.
There are two algorithms to perform searching, Linear Search and Binary Search. We will discuss each one
of them later in this tutorial.
5) Sorting: The process of arranging the data structure in a specific order is known as Sorting. There are
many algorithms that can be used to perform sorting, for example, insertion sort, selection sort, bubble sort,
etc.
6) Merging: When two lists List A and List B of size M and N respectively, of similar type of elements,
clubbed or joined to produce the third list, List C of size (M+N), then this process is called merging
ALGORITHMS
The word Algorithm means “a process or set of rules to be followed in calculations or other problem-
solving operations”. Therefore Algorithm refers to a set of rules/instructions that step-by-step define how
a work is to be executed upon in order to get the expected results.
It can be understood by taking an example of cooking a new recipe. To cook a new recipe, one reads the
instructions and steps and execute them one by one, in the given sequence. The result thus obtained is
the new dish cooked perfectly. Similarly, algorithms help to do a task in programming to get the
expected output.
The Algorithm designed are language-independent, i.e. they are just plain instructions that can be
implemented in any language, and yet the output will be the same, as expected.
project on data structures and algorithm
CHARACTERISTICS OF ALGORITHMS
ALGORITHM ANALYSIS
Best case = fastest time to complete, with optimal inputs chosen.
For example, the best case for a sorting algorithm would be data that's already sorted.
Worst case = slowest time to complete, with pessimal inputs, are chosen. For example, the worst
case for a sorting algorithm might be data that are sorted in reverse order (but it depends on the
particular algorithm).
Average case = arithmetic mean. Run the algorithm many times, using many different inputs of
size n that come from some distribution that generates these inputs (in the simplest case, all the
possible inputs are equally likely), compute the total running time (by adding the individual
times), and divide by the number of trials. You may also need to normalize the results based on
the size of the input sets.
ASYMPTOTIC NOTATIONS
Asymptotic notations are the mathematical notations used to describe the running time of an
algorithm when the input tends towards a particular value or a limiting value.
For example: In bubble sort, when the input array is already sorted, the time taken by the algorithm is
linear i.e. the best case.
But, when the input array is in reverse condition, the algorithm takes the maximum time (quadratic)
to sort the elements i.e. the worst case.
When the input array is neither sorted nor in reverse order, then it takes average time. These
durations are denoted using asymptotic notations.
There are mainly three asymptotic notations:
• Big-O notation
• Omega notation
• Theta notation
Mixed Notation: Mixed notation consist of two or more type of notation. It is a mixture of letter and
number, i.e. Arabic numeral and Roman letter (0-9) + (A-Z). it found in UDC, LC, CC, BC & SC
scheme.
For example:
LCq- Science
QC- Physic
QC1- Periodicals.
TYPES OF NOTATIONS
TYPES OF NOTATIONS
BIG Oh
(O)
NOTATION
S
SMALL Oh
(o)
NOTATION
S
BIG
OMEGA
NOTATION
SMALL
OMEGA
(ω)
THETA (θ)
NOTATION
S
BIG OH (O) NOTATIONS
Big-Oh (O) notation gives an upper bound for a function f(n) to within a constant factor.
We write f(n) = O(g(n)), If there are positive constants n0 and c such that, to the right of n0 the
f(n) always lies on or below c*g(n).
O(g(n)) = { f(n) : There exist positive constant c and n0 such that 0 ≤ f(n) ≤ c g(n), for all n ≤ n0}
SMALL OH (O) NOTATIONS
Small-o, commonly written as o, is an Asymptotic Notation to denote the upper bound (that is not
asymptotically tight) on the growth rate of runtime of an algorithm.
f(n) is o(g(n)), if for all real constants c (c > 0) and n0 (n0 > 0), f(n) is < c g(n) for every input size n (n >
n0).
The definitions of O-notation and o-notation are similar. The main difference is that in f(n) = O(g(n)),
the bound f(n) <= g(n) holds for some constant c > 0, but in f(n) = o(g(n)), the bound f(n) < c g(n) holds
for all constants c > 0.
BIG OMEGA (Ω) NOTATIONS
Big-Omega (Ω) notation gives a lower bound for a function f(n) to within a constant factor.
We write f(n) = Ω(g(n)), If there are positive constants n0 and c such that, to the right of n0 the f(n)
always lies on or above c*g(n).
Ω(g(n)) = { f(n) : There exist positive constant c and n0 such that 0 ≤ c g(n) ≤ f(n), for all n ≤ n0}
SMALL OMEGA (ꞷ) NOTATION
Let f(n) and g(n) be functions that map positive integers to positive real numbers. We say that f(n) is
ω(g(n)) (or f(n) ∈ ω(g(n))) if for any real constant c > 0, there exists an integer constant n0 ≥ 1 such
that f(n) > c * g(n) ≥ 0 for every integer n ≥ n0.
f(n) has a higher growth rate than g(n) so main difference between Big Omega (Ω) and little omega (ω)
lies in their definitions.In the case of Big Omega f(n)=Ω(g(n)) and the bound is 0<=cg(n)<=f(n), but in
case of little omega, it is true for 0<=c*g(n)<f(n).
The relationship between Big Omega (Ω) and Little Omega (ω) is similar to that of Big-Ο and
Little o except that now we are looking at the lower bounds. Little Omega (ω) is a rough estimate
of the order of the growth whereas Big Omega (Ω) may represent exact order of growth. We use ω
notation to denote a lower bound that is not asymptotically tight.
And, f(n) ∈ ω(g(n)) if and only if g(n) ∈ ο((f(n)).
In mathematical relation,
if f(n) ∈ ω(g(n)) then,
lim f(n)/g(n) = ∞
n→∞
Example:
Prove that 4n + 6 ∈ ω(1);
the little omega(ο) running time can
be proven by applying limit formula
given below.
if lim f(n)/g(n) = ∞ then functions f(n)
is ω(g(n))
n→∞
here,we have functions f(n)=4n+6 and
g(n)=1
lim (4n+6)/(1) = ∞
n→∞
and,also for any c we can get n0 for
this inequality 0 <= c*g(n) < f(n), 0 <=
c*1 < 4n+6
Hence proved.
ARRAY
An array is defined as the collection of similar type of data items stored at contiguous memory
locations. Arrays are the derived data type in C programming language which can store the
primitive type of data such as int, char, double, float, etc. It also has the capability to store the
collection of derived data types, such as pointers, structure, etc. The array is the simplest data
structure where each data element can be randomly accessed by using its index number.
C array is beneficial if you have to store similar elements. For example, if we want to store the
marks of a student in 6 subjects, then we don't need to define different variables for the marks in
the different subject. Instead of that, we can define an array which can store the marks in each
subject at the contiguous memory locations.
By using the array, we can access the elements easily. Only a few lines of code are required to
access the elements of the array.
ONE DIMENSIONAL ARRAY
One dimensional array is an array that has only one subscript specification that is needed to
specify a particular element of an array. A one-dimensional array is a structured collection of
components (often called array elements) that can be accessed individually by specifying the
position of a component with a single index value.
Syntax: data-type arr_name[array_size];
Rules for Declaring One Dimensional Array
An array variable must be declared before being used in a program.
The declaration must have a data type(int, float, char, double, etc.), variable name, and
subscript.
The subscript represents the size of the array. If the size is declared as 10, programmers can
store 10 elements.
An array index always starts from 0. For example, if an array variable is declared as s[10], then
it ranges from 0 to 9.
Each array element stored in a separate memory location.
OPERATION OF 1D ARRAY
Following are the basic operations supported by an array.
 Traverse − print all the array elements one by one.
 Insertion − Adds an element at the given index.
 Deletion − Deletes an element at the given index.
 Search − Searches an element using the given index or
by the value.
 Update − Updates an element at the given index.
 Sorting – Arranging in descending or ascending order
 Merging – concatenate two ways into third array or
merge directly into third arrays where two arrays are
already sorted
TRAVERSING AN ARRAY
• Traversal operation in array or simply traversing an array means,
Accessing or printing each element of an array exactly once so that the
data item (values) of the array can be checked or used as part of some other
operation or process (This accessing and processing is sometimes called
“visiting” the array).
• 📝 Note: Accessing or printing of elements always takes place one by one.
Algorithm for Traversing an Array:
Step 01: Start
Step 02: [Initialize counter variable. ] Set i = LB.
Step 03: Repeat for i = LB to UB.
Step 04: Apply process to arr[i].
Step 05: [End of loop. ]
Step 06: Stop
Variables used:
i : Loop counter or counter variable for the for loop.
arr : Array name.
LB : Lower bound.
UB : Upper bound.
INSERTION OF AN ARRAY
An array is a collection of items stored at contiguous memory locations. In this
article, we will see how to insert an element in an array in C.
Given an array arr of size n, this article tells how to insert an element x in this array
arr at a specific position pos.
Approach:
Here’s how to do it.
First get the element to be inserted, say x
Then get the position at which this element is to be inserted, say pos
Then shift the array elements from this position to one position forward, and do this for all
the other elements next to pos.
Insert the element x now at the position pos, as this is now empty.
SEARCHING IN AN ARRAY
Searching in data structure refers to the process of finding the required information from a
collection of items stored as elements in the computer memory. These sets of items are in
different forms, such as an array, linked list, graph, or tree. Another way to define searching in
the data structures is by locating the desired element of specific characteristics in a collection of
items.
Searching Methods
Searching in the data structure can be done by applying searching algorithms to check for or
extract an element from any form of stored data structure.
These algorithms are classified according to the type of search operation they perform, such as:
Sequential search
The list or array of elements is traversed sequentially while checking every component of the
set.
For example – Linear Search.
Interval Search
The interval search includes algorithms that are explicitly designed for searching in sorted data
structures. In terms of efficiency, these algorithms are far better than linear search algorithms.
Example- Logarithmic Search, Binary search.
SORTING IN AN ARRAY
Sorting refers to the operation or technique of arranging and rearranging sets of data in some
specific order. A collection of records called a list where every record has one or more fields. The
fields which contain a unique value for each record is termed as the key field. For example, a
phone number directory can be thought of as a list where each record has three fields - 'name' of
the person, 'address' of that person, and their 'phone numbers'. Being unique phone number can
work as a key to locate any record in the list.
Sorting is the operation performed to arrange the records of a table or list in some order
according to some specific ordering criterion. Sorting is performed according to some key value of
each record.
The records are either sorted either numerically or alphanumerically. The records are then
arranged in ascending or descending order depending on the numerical value of the key. Here is
an example, where the sorting of a lists of marks obtained by a student in any particular subject
of a class.
The techniques of sorting can be divided into two categories. These are:
Internal Sorting
External Sorting
Internal Sorting: If all the data that is to be sorted can be adjusted at a time in the main memory, the
internal sorting method is being performed.
External Sorting: When the data that is to be sorted cannot be accommodated in the memory at the
same time and some has to be kept in auxiliary memory such as hard disk, floppy disk, magnetic tapes
etc, then external sorting methods are performed.
TYPES OF SORTING
 Bubble Sort
 Selection Sort
 Merge Sort
 Insertion Sort
 Quick Sort
 Heap Sort
 Count Sort
MERGING OF AN ARRAY
Merging two arrays means combining two separate arrays into one single array. For instance, if
the first array consists of 3 elements and the second array consists of 5 elements then the
resulting array consists of 8 elements. This resulting array is known as a merged array. Before
moving forward, if you are not familiar with the concept of the array then, do check the article on
Arrays in C.
We are given two sorted arrays and our task is to merge
these two sorted arrays.
Input: First Array: 5 4 3 2 1
Second Array: 9 8 7 6 5
Output: Merged sorted Array: 9 8 7 6 5 5 4 3 2 1
project on data structures and algorithm
TWO DIMENSIONAL ARRAY
A one-dimensional array can be seen as data elements organised in a row. A two-dimensional array
is similar to a one-dimensional array, but it can be visualised as a grid (or table) with rows and
columns.
For example, a nine-by-nine grid could be referenced with numbers for each row and letters for each
column. A nine-by-nine, two-dimensional array could be declared with a statement such as:
game [9][9]
Many games use two dimensional arrays to plot the visual environment of a game. Positions in a
two dimensional array are referenced like a map using horizontal and vertical reference numbers.
They are sometimes called matrices.
Declaration of two dimensional Array in C
The syntax to declare the 2D array is given below.
data_type array_name[rows][columns];
Consider the following example.
int twodimen[4][3];
Here, 4 is the number of rows, and 3 is the number of columns
Initialization of 2D Array in C
In the 1D array, we don't need to specify the size of the array if the declaration and
initialization are being done simultaneously. However, this will not work with 2D
arrays. We will have to define at least the second dimension of the array. The two-
dimensional array can be declared and defined in the following way.
int arr[4][3]={{1,2,3},{2,3,4},{3,4,5},{4,5,6}};
LINEAR SEARCH
In this article, we will discuss the Linear Search Algorithm. Searching is the process of finding some
particular element in the list. If the element is present in the list, then the process is called successful,
and the process returns the location of that element; otherwise, the search is called unsuccessful.
Two popular search methods are Linear Search and Binary Search. So, here we will discuss the popular
searching technique, i.e., Linear Search Algorithm.
Linear search is also called as sequential search algorithm. It is the simplest searching algorithm. In
Linear search, we simply traverse the list completely and match each element of the list with the item
whose location is to be found. If the match is found, then the location of the item is returned; otherwise,
the algorithm returns NULL.
It is widely used to search an element from the unordered list, i.e., the list in which items are not sorted.
The worst-case time complexity of linear search is O(n).
The steps used in the implementation of Linear Search are listed as follows -
First, we have to traverse the array elements using a for loop.
In each iteration of for loop, compare the search element with the current array element, and -
If the element matches, then return the index of the corresponding array element.
If the element does not match, then move to the next element.
If there is no match or the search element is not present in the given array, return -1.
Now, let's see the algorithm of linear search.
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
// C code to linearly search x in arr[]. If x
// is present then return its location, otherwise
// return -1
#include <stdio.h>
int search(int arr[], int n, int x)
{
int i;
for (i = 0; i < n; i++)
if (arr[i] == x)
return i;
return -1;
}
// Driver code
int main(void)
{
int arr[] = { 2, 3, 4, 10, 40 };
int x = 10;
int n = sizeof(arr) / sizeof(arr[0]);
// Function call
int result = search(arr, n, x);
(result == -1)
? printf("Element is not present in array")
: printf("Element is present at index %d", result);
return 0;
}
BINARY SEARCH
• Given a sorted array arr[] of n elements, write a function to search a given element x in
arr[].
• A simple approach is to do a linear search. The time complexity of the above algorithm is
O(n). Another approach to perform the same task is using Binary Search.
• Binary Search: Search a sorted array by repeatedly dividing the search interval in half.
Begin with an interval covering the whole array. If the value of the search key is less
than the item in the middle of the interval, narrow the interval to the lower half.
Otherwise, narrow it to the upper half. Repeatedly check until the value is found or the
interval is empty.
• The idea of binary search is to use the information that the array is sorted and reduce
the time complexity to O(Log n).
project on data structures and algorithm
// C program to implement recursive Binary Search
#include <stdio.h>
// A recursive binary search function. It returns
// location of x in given array arr[l..r] is present,
// otherwise -1
int binarySearch(int arr[], int l, int r, int x)
{
if (r >= l) {
int mid = l + (r - l) / 2;
// If the element is present at the middle
// itself
if (arr[mid] == x)
return mid;
// If element is smaller than mid, then
// it can only be present in left subarray
if (arr[mid] > x)
return binarySearch(arr, l, mid - 1, x);
// Else the element can only be present
// in right subarray
return binarySearch(arr, mid + 1, r, x);
}
// We reach here when element is not
// present in array
return -1;
}
int main(void)
{
int arr[] = { 2, 3, 4, 10, 40 };
int n = sizeof(arr) / sizeof(arr[0]);
int x = 10;
int result = binarySearch(arr, 0, n - 1, x);
(result == -1)
? printf("Element is not present in array")
: printf("Element is present at index %d",
result);
return 0;
}
BUBBLE SORT
Bubble sort, also referred to as comparison sort, is a simple sorting algorithm that repeatedly
goes through the list, compares adjacent elements and swaps them if they are in the wrong order.
This is the most simplest algorithm and inefficient at the same time. Yet, it is very much
necessary to learn about it as it represents the basic foundations of sorting.
Although it is simple to use, it is primarily used as an educational tool because the performance
of bubble sort is poor in the real world. It is not suitable for large data sets. The average and
worst-case complexity of Bubble sort is O(n2), where n is a number of items.
Bubble short is majorly used where -
• complexity does not matter
• simple and shortcode is preferred
// Bubble sort in C
#include <stdio.h>
// perform the bubble sort
void bubbleSort(int array[], int size) {
// loop to access each array element
for (int step = 0; step < size - 1; ++step) {
// loop to compare array elements
for (int i = 0; i < size - step - 1; ++i) {
// compare two adjacent elements
// change > to < to sort in descending order
if (array[i] > array[i + 1]) {
// swapping occurs if elements
// are not in the intended order
int temp = array[i];
array[i] = array[i + 1];
array[i + 1] = temp;
}
}
}
}
// print array
void printArray(int array[], int size) {
for (int i = 0; i < size; ++i) {
printf("%d ", array[i]);
}
printf("n");
}
int main() {
int data[] = {-2, 45, 0, 11, -9};
// find the array's length
int size = sizeof(data) / sizeof(data[0]);
bubbleSort(data, size);
printf("Sorted Array in Ascending Order:n");
printArray(data, size);
}
SELECTION SORT
The selection sort algorithm sorts an array by
repeatedly finding the minimum element (considering
ascending order) from unsorted part and putting it at
the beginning. The algorithm maintains two subarrays
in a given array.
1) The subarray which is already sorted.
2) Remaining subarray which is unsorted.
In every iteration of selection sort, the minimum
element (considering ascending order) from the
unsorted subarray is picked and moved to the sorted
subarray.
Following example explains the above steps:
arr[] = 64 25 12 22 11
// Find the minimum element in arr[0...4]
// and place it at beginning
11 25 12 22 64
// Find the minimum element in arr[1...4]
// and place it at beginning of arr[1...4]
11 12 25 22 64
// Find the minimum element in arr[2...4]
// and place it at beginning of arr[2...4]
11 12 22 25 64
// Find the minimum element in arr[3...4]
// and place it at beginning of arr[3...4]
11 12 22 25 64
// C program for implementation of selection sort
#include <stdio.h>
void swap(int *xp, int *yp)
{
int temp = *xp;
*xp = *yp;
*yp = temp;
}
void selectionSort(int arr[], int n)
{
int i, j, min_idx;
// One by one move boundary of unsorted subarray
for (i = 0; i < n-1; i++)
{
// Find the minimum element in unsorted array
min_idx = i;
for (j = i+1; j < n; j++)
if (arr[j] < arr[min_idx])
min_idx = j;
// Swap the found minimum element with the first element
swap(&arr[min_idx], &arr[i]);
}
}
/* Function to print an array */
void printArray(int arr[], int size)
{
int i;
for (i=0; i < size; i++)
printf("%d ", arr[i]);
printf("n");
}
// Driver program to test above functions
int main()
{
int arr[] = {64, 25, 12, 22, 11};
int n = sizeof(arr)/sizeof(arr[0]);
selectionSort(arr, n);
printf("Sorted array: n");
printArray(arr, n);
return 0;
}
MERGE SORT
In this article, we will discuss the merge sort Algorithm. Merge sort is the sorting technique
that follows the divide and conquer approach. This article will be very helpful and interesting to
students as they might face merge sort as a question in their examinations. In coding or
technical interviews for software engineers, sorting algorithms are widely asked. So, it is
important to discuss the topic.
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.
/* C program for Merge Sort */
#include <stdio.h>
#include <stdlib.h>
// Merges two subarrays of arr[].
// First subarray is arr[l..m]
// Second subarray is arr[m+1..r]
void merge(int arr[], int l, int m, int r)
{
int i, j, k;
int n1 = m - l + 1;
int n2 = r - m;
/* create temp arrays */
int L[n1], R[n2];
/* Copy data to temp arrays L[] and R[] */
for (i = 0; i < n1; i++)
L[i] = arr[l + i];
for (j = 0; j < n2; j++)
R[j] = arr[m + 1 + j];
/* Merge the temp arrays back into arr[l..r]*/
i = 0; // Initial index of first subarray
j = 0; // Initial index of second subarray
k = l; // Initial index of merged subarray
while (i < n1 && j < n2) {
if (L[i] <= R[j]) {
arr[k] = L[i];
i++;
}
else {
arr[k] = R[j];
j++;
}
k++;
}
/* Copy the remaining elements of L[], if there
are any */
while (i < n1) {
arr[k] = L[i];
i++;
k++;
}
/* Copy the remaining elements of R[], if there
are any */
while (j < n2) {
arr[k] = R[j];
j++;
k++;
}
}
/* l is for left index and r is right index of the
sub-array of arr to be sorted */
void mergeSort(int arr[], int l, int r)
{
INSERTION SORT
Insertion sort is a simple sorting algorithm that works similar to the way you sort playing cards in your
hands. The array is virtually split into a sorted and an unsorted part. Values from the unsorted part are
picked and placed at the correct position in the sorted part.
Algorithm
To sort an array of size n in ascending order:
1: Iterate from arr[1] to arr[n] over the array.
2: Compare the current element (key) to its predecessor.
3: If the key element is smaller than its predecessor, compare it to the elements before. Move the
greater elements one position up to make space for the swapped element.
Another Example:
12, 11, 13, 5, 6
Let us loop for i = 1 (second element of the array) to 4
(last element of the array)
i = 1. Since 11 is smaller than 12, move 12 and insert 11
before 12
11, 12, 13, 5, 6
i = 2. 13 will remain at its position as all elements in A[0..I-
1] are smaller than 13
11, 12, 13, 5, 6
i = 3. 5 will move to the beginning and all other elements
from 11 to 13 will move one position ahead of their current
position.
5, 11, 12, 13, 6
i = 4. 6 will move to position after 5, and elements from 11
to 13 will move one position ahead of their current
position.
5, 6, 11, 12, 13
Time Complexity: O(n^2)
Auxiliary Space: O(1)
Boundary Cases: Insertion sort takes maximum time to sort if elements are sorted in reverse order.
And it takes minimum time (Order of n) when elements are already sorted.
Algorithmic Paradigm: Incremental Approach
Sorting In Place: Yes
Stable: Yes
Online: Yes
Uses: Insertion sort is used when number of elements is small. It can also be useful when input array
is almost sorted, only few elements are misplaced in complete big array.
What is Binary Insertion Sort?
We can use binary search to reduce the number of comparisons in normal insertion sort. Binary
Insertion Sort uses binary search to find the proper location to insert the selected item at each
iteration. In normal insertion, sorting takes O(i) (at ith iteration) in worst case. We can reduce it to
O(logi) by using binary search. The algorithm, as a whole, still has a running worst case running time
of O(n^2) because of the series of swaps required for each insertion. Refer this for implementation.
How to implement Insertion Sort for Linked List?
Below is simple insertion sort algorithm for linked list.
// C program for insertion sort
#include <math.h>
#include <stdio.h>
void insertionSort(int arr[], int n)
{
int i, key, j;
for (i = 1; i < n; i++) {
key = arr[i];
j = i - 1;
while (j >= 0 && arr[j] > key) {
arr[j + 1] = arr[j];
j = j - 1;
}
arr[j + 1] = key;
}
}
// A utility function to print an array of size n
void printArray(int arr[], int n)
{
int i;
for (i = 0; i < n; i++)
printf("%d ", arr[i]);
printf("n");
}
/* Driver program to test insertion sort */
int main()
{
int arr[] = { 12, 11, 13, 5, 6 };
int n = sizeof(arr) / sizeof(arr[0]);
insertionSort(arr, n);
printArray(arr, n);
return 0; }}
QUICK SORT
QuickSort
•Difficulty Level : Medium
•Last Updated : 25 Jan, 2022
Like Merge Sort, QuickSort is a Divide and Conquer algorithm. It picks an element as pivot and
partitions the given array around the picked pivot. There are many different versions of quickSort that
pick pivot in different ways.
1.Always pick first element as pivot.
2.Always pick last element as pivot (implemented below)
3.Pick a random element as pivot.
4.Pick median as pivot.
The key process in quickSort is partition(). Target of partitions is, given an array and an element x of
array as pivot, put x at its correct position in sorted array and put all smaller elements (smaller than x)
before x, and put all greater elements (greater than x) after x. All this should be done in linear time.
/ Quick sort in C
#include <stdio.h>
// function to swap elements
void swap(int *a, int *b) {
int t = *a;
*a = *b;
*b = t;
}
// function to find the partition position
int partition(int array[], int low, int high) {
// select the rightmost element as pivot
int pivot = array[high];
// pointer for greater element
int i = (low - 1);
// pointer for greater element
int i = (low - 1);
// traverse each element of the array
// compare them with the pivot
for (int j = low; j < high; j++) {
if (array[j] <= pivot) {
// if element smaller than pivot is found
// swap it with the greater element pointed by i
i++;
// swap element at i with element at j
swap(&array[i], &array[j]);
}
}
// swap the pivot element with the greater element at i
swap(&array[i + 1], &array[high]);
// return the partition point
return (i + 1);
}
void quickSort(int array[], int low, int high) {
if (low < high) {
// find the pivot element such that
// elements smaller than pivot are on left of pivot
// elements greater than pivot are on right of pivot
int pi = partition(array, low, high);
// recursive call on the left of pivot
quickSort(array, low, pi - 1);
// recursive call on the right of pivot
quickSort(array, pi + 1, high);
}
}
// function to print array elements
void printArray(int array[], int size) {
for (int i = 0; i < size; ++i) {
printf("%d ", array[i]);
}
printf("n");
}
// main function
int main() {
int data[] = {8, 7, 2, 1, 0, 9, 6};
int n = sizeof(data) / sizeof(data[0]);
printf("Unsorted Arrayn");
printArray(data, n);
// perform quicksort on data
quickSort(data, 0, n - 1);
printf("Sorted array in ascending order: n");
printArray(data, n);
}
COUNT SORT
Counting sort is a sorting technique based on keys between a specific range. It works by counting the
number of objects having distinct key values (kind of hashing). Then doing some arithmetic to
calculate the position of each object in the output sequence.
Let us understand it with the help of an example.
For simplicity, consider the data in the range 0 to 9.
Input data: 1, 4, 1, 2, 7, 5, 2
1) Take a count array to store the count of each unique object.
Index: 0 1 2 3 4 5 6 7 8 9
Count: 0 2 2 0 1 1 0 1 0 0
2) Modify the count array such that each element at each index
stores the sum of previous counts.
Index: 0 1 2 3 4 5 6 7 8 9
Count: 0 2 4 4 5 6 6 7 7 7
The modified count array indicates the position of each object in
the output sequence.
3) Rotate the array clockwise for one time.
Index: 0 1 2 3 4 5 6 7 8 9
Count: 0 0 2 4 4 5 6 6 7 7
4) Output each object from the input sequence followed by
increasing its count by 1.
Process the input data: 1, 4, 1, 2, 7, 5, 2. Position of 1 is 0.
Put data 1 at index 0 in output. Increase count by 1 to place
next data 1 at an index 1 greater than this index.
Time Complexity: O(n+k) where n is the number of elements in input array and k
is the range of input.
Auxiliary Space: O(n+k)
The problem with the previous counting sort was that we could not sort the
elements if we have negative numbers in it. Because there are no negative array
indices. So what we do is, we find the minimum element and we will store count of
that minimum element at zero index.
// C Program for counting sort
#include <stdio.h>
#include <string.h>
#define RANGE 255
// The main function that sort the given string arr[] in
// alphabetical order
void countSort(char arr[])
{
// The output character array that will have sorted arr
char output[strlen(arr)];
// Create a count array to store count of individual
// characters and initialize count array as 0
int count[RANGE + 1], i;
memset(count, 0, sizeof(count));
// Store count of each character
for (i = 0; arr[i]; ++i)
++count[arr[i]];
// Change count[i] so that count[i] now contains actual
// position of this character in output array
for (i = 1; i <= RANGE; ++i)
count[i] += count[i - 1];
// Build the output character array
for (i = 0; arr[i]; ++i) {
output[count[arr[i]] - 1] = arr[i];
--count[arr[i]];
}
/*
For Stable algorithm
for (i = sizeof(arr)-1; i>=0; --i)
{
output[count[arr[i]]-1] = arr[i];
--count[arr[i]];
}
For Logic : See implementation
*/
// Copy the output array to arr, so that arr now
// contains sorted characters
for (i = 0; arr[i]; ++i)
arr[i] = output[i];
}
// Driver program to test above function
int main()
{
char arr[] = "geeksforgeeks"; //"applepp";
countSort(arr);
printf("Sorted character array is %sn", arr);
return 0;
}

More Related Content

Similar to project on data structures and algorithm (20)

Datastructures and algorithms prepared by M.V.Brehmanada Reddy
Datastructures and algorithms prepared by M.V.Brehmanada Reddy
Malikireddy Bramhananda Reddy
 
Unit-I PPT hususi sisooshsgv. Eijeieieooekejj
Unit-I PPT hususi sisooshsgv. Eijeieieooekejj
sanketkurve7
 
DATA STRUCTURE AND ALGORITHMS
DATA STRUCTURE AND ALGORITHMS
removed_8057d320f6c8601c14a895598b86eacb
 
Data structures - Introduction
Data structures - Introduction
DeepaThirumurugan
 
Data Structure & Algorithm.pptx
Data Structure & Algorithm.pptx
Mumtaz
 
introduction about data structure_i.pptx
introduction about data structure_i.pptx
poonamsngr
 
Introduction to data structure
Introduction to data structure
sunilchute1
 
Introduction to data structure
Introduction to data structure
sunilchute1
 
data structures and algorithm Cha 1and 2.doc
data structures and algorithm Cha 1and 2.doc
ephremmulu486
 
CSE 443 (1).pptx
CSE 443 (1).pptx
JayaKrishna636858
 
Chapter 1 _edited.pptx.software engineering
Chapter 1 _edited.pptx.software engineering
kuruabeje7
 
DSA - Copy.pptx
DSA - Copy.pptx
BishalChowdhury10
 
Data Structure and Algorithms by Sabeen Memon03.pptx
Data Structure and Algorithms by Sabeen Memon03.pptx
msoomar8611
 
Introduction to data structures (ss)
Introduction to data structures (ss)
Madishetty Prathibha
 
UNIT I - Data Structures.pdf
UNIT I - Data Structures.pdf
KPRevathiAsstprofITD
 
Datastructures Notes
Datastructures Notes
Ranjithkumar C
 
Which data structure is it? What are the various data structure kinds and wha...
Which data structure is it? What are the various data structure kinds and wha...
Tutort Academy
 
Chapter 1 Data structure _Algorithms.pptx
Chapter 1 Data structure _Algorithms.pptx
BifaHirpo1
 
TSAT Presentation1.pptx
TSAT Presentation1.pptx
Rajitha Reddy Alugati
 
Chapter 2.2 data structures
Chapter 2.2 data structures
sshhzap
 
Datastructures and algorithms prepared by M.V.Brehmanada Reddy
Datastructures and algorithms prepared by M.V.Brehmanada Reddy
Malikireddy Bramhananda Reddy
 
Unit-I PPT hususi sisooshsgv. Eijeieieooekejj
Unit-I PPT hususi sisooshsgv. Eijeieieooekejj
sanketkurve7
 
Data structures - Introduction
Data structures - Introduction
DeepaThirumurugan
 
Data Structure & Algorithm.pptx
Data Structure & Algorithm.pptx
Mumtaz
 
introduction about data structure_i.pptx
introduction about data structure_i.pptx
poonamsngr
 
Introduction to data structure
Introduction to data structure
sunilchute1
 
Introduction to data structure
Introduction to data structure
sunilchute1
 
data structures and algorithm Cha 1and 2.doc
data structures and algorithm Cha 1and 2.doc
ephremmulu486
 
Chapter 1 _edited.pptx.software engineering
Chapter 1 _edited.pptx.software engineering
kuruabeje7
 
Data Structure and Algorithms by Sabeen Memon03.pptx
Data Structure and Algorithms by Sabeen Memon03.pptx
msoomar8611
 
Introduction to data structures (ss)
Introduction to data structures (ss)
Madishetty Prathibha
 
Which data structure is it? What are the various data structure kinds and wha...
Which data structure is it? What are the various data structure kinds and wha...
Tutort Academy
 
Chapter 1 Data structure _Algorithms.pptx
Chapter 1 Data structure _Algorithms.pptx
BifaHirpo1
 
Chapter 2.2 data structures
Chapter 2.2 data structures
sshhzap
 

Recently uploaded (20)

THERAPEUTIC COMMUNICATION included definition, characteristics, nurse patient...
THERAPEUTIC COMMUNICATION included definition, characteristics, nurse patient...
parmarjuli1412
 
Vikas Bansal Himachal Pradesh: A Visionary Transforming Himachal’s Educationa...
Vikas Bansal Himachal Pradesh: A Visionary Transforming Himachal’s Educationa...
Himalayan Group of Professional Institutions (HGPI)
 
Exploring Ocean Floor Features for Middle School
Exploring Ocean Floor Features for Middle School
Marie
 
Sustainable Innovation with Immersive Learning
Sustainable Innovation with Immersive Learning
Leonel Morgado
 
Unit- 4 Biostatistics & Research Methodology.pdf
Unit- 4 Biostatistics & Research Methodology.pdf
KRUTIKA CHANNE
 
LDMMIA Spring Ending Guest Grad Student News
LDMMIA Spring Ending Guest Grad Student News
LDM & Mia eStudios
 
FEBA Sofia Univercity final diplian v3 GSDG 5.2025.pdf
FEBA Sofia Univercity final diplian v3 GSDG 5.2025.pdf
ChristinaFortunova
 
MATERI PPT TOPIK 4 LANDASAN FILOSOFIS PENDIDIKAN
MATERI PPT TOPIK 4 LANDASAN FILOSOFIS PENDIDIKAN
aditya23173
 
Revista digital preescolar en transformación
Revista digital preescolar en transformación
guerragallardo26
 
Publishing Your Memoir with Brooke Warner
Publishing Your Memoir with Brooke Warner
Brooke Warner
 
LDMMIA GRAD Student Check-in Orientation Sampler
LDMMIA GRAD Student Check-in Orientation Sampler
LDM & Mia eStudios
 
Capitol Doctoral Presentation -June 2025.pptx
Capitol Doctoral Presentation -June 2025.pptx
CapitolTechU
 
GEOGRAPHY-Study Material [ Class 10th] .pdf
GEOGRAPHY-Study Material [ Class 10th] .pdf
SHERAZ AHMAD LONE
 
Webcrawler_Mule_AIChain_MuleSoft_Meetup_Hyderabad
Webcrawler_Mule_AIChain_MuleSoft_Meetup_Hyderabad
Veera Pallapu
 
The Man In The Back – Exceptional Delaware.pdf
The Man In The Back – Exceptional Delaware.pdf
dennisongomezk
 
Allomorps and word formation.pptx - Google Slides.pdf
Allomorps and word formation.pptx - Google Slides.pdf
Abha Pandey
 
LDMMIA Free Reiki Yoga S9 Grad Level Intuition II
LDMMIA Free Reiki Yoga S9 Grad Level Intuition II
LDM & Mia eStudios
 
BUSINESS QUIZ PRELIMS | QUIZ CLUB OF PSGCAS | 9 SEPTEMBER 2024
BUSINESS QUIZ PRELIMS | QUIZ CLUB OF PSGCAS | 9 SEPTEMBER 2024
Quiz Club of PSG College of Arts & Science
 
Chalukyas of Gujrat, Solanki Dynasty NEP.pptx
Chalukyas of Gujrat, Solanki Dynasty NEP.pptx
Dr. Ravi Shankar Arya Mahila P. G. College, Banaras Hindu University, Varanasi, India.
 
Unit 3 Poster Sketches with annotations.pptx
Unit 3 Poster Sketches with annotations.pptx
bobby205207
 
THERAPEUTIC COMMUNICATION included definition, characteristics, nurse patient...
THERAPEUTIC COMMUNICATION included definition, characteristics, nurse patient...
parmarjuli1412
 
Exploring Ocean Floor Features for Middle School
Exploring Ocean Floor Features for Middle School
Marie
 
Sustainable Innovation with Immersive Learning
Sustainable Innovation with Immersive Learning
Leonel Morgado
 
Unit- 4 Biostatistics & Research Methodology.pdf
Unit- 4 Biostatistics & Research Methodology.pdf
KRUTIKA CHANNE
 
LDMMIA Spring Ending Guest Grad Student News
LDMMIA Spring Ending Guest Grad Student News
LDM & Mia eStudios
 
FEBA Sofia Univercity final diplian v3 GSDG 5.2025.pdf
FEBA Sofia Univercity final diplian v3 GSDG 5.2025.pdf
ChristinaFortunova
 
MATERI PPT TOPIK 4 LANDASAN FILOSOFIS PENDIDIKAN
MATERI PPT TOPIK 4 LANDASAN FILOSOFIS PENDIDIKAN
aditya23173
 
Revista digital preescolar en transformación
Revista digital preescolar en transformación
guerragallardo26
 
Publishing Your Memoir with Brooke Warner
Publishing Your Memoir with Brooke Warner
Brooke Warner
 
LDMMIA GRAD Student Check-in Orientation Sampler
LDMMIA GRAD Student Check-in Orientation Sampler
LDM & Mia eStudios
 
Capitol Doctoral Presentation -June 2025.pptx
Capitol Doctoral Presentation -June 2025.pptx
CapitolTechU
 
GEOGRAPHY-Study Material [ Class 10th] .pdf
GEOGRAPHY-Study Material [ Class 10th] .pdf
SHERAZ AHMAD LONE
 
Webcrawler_Mule_AIChain_MuleSoft_Meetup_Hyderabad
Webcrawler_Mule_AIChain_MuleSoft_Meetup_Hyderabad
Veera Pallapu
 
The Man In The Back – Exceptional Delaware.pdf
The Man In The Back – Exceptional Delaware.pdf
dennisongomezk
 
Allomorps and word formation.pptx - Google Slides.pdf
Allomorps and word formation.pptx - Google Slides.pdf
Abha Pandey
 
LDMMIA Free Reiki Yoga S9 Grad Level Intuition II
LDMMIA Free Reiki Yoga S9 Grad Level Intuition II
LDM & Mia eStudios
 
Unit 3 Poster Sketches with annotations.pptx
Unit 3 Poster Sketches with annotations.pptx
bobby205207
 
Ad

project on data structures and algorithm

  • 1. PROJECT ON- MODULE 1 (DSA) FACULTY NAME – SACHIN AGARWAL PRESENTED BY – ANUJ KUMAR ROLL NO -2011008 REG NO. – 20030480006 BRANCH – INFORMATION TECHNOLOGY COLLEGE NAME – BIT SINDRI
  • 2. TOPICS COVERED  INTRODUCTION TO DATA STRUCTURES  ALGORITHMS AND ASYMPTOMATIC NOTATIONS  ARRAY  STACK  LINKED LIST
  • 3. INTRODUCTION TO DATA STRUCTURES • Data Structure can be defined as the group of data elements which provides an efficient way of storing and organising data in the computer so that it can be used efficiently. Some examples of Data Structures are arrays, Linked List, Stack, Queue, etc. Data Structures are widely used in almost every aspect of Computer Science i.e. Operating System, Compiler Design, Artifical intelligence, Graphics and many more. • Data Structures are the main part of many computer science algorithms as they enable the programmers to handle the data in an efficient way. It plays a vital role in enhancing the performance of a software or a program as the main function of the software is to store and retrieve the user's data as fast as possible.
  • 4. NEED OF DATA STRUCTURE • As applications are getting complexed and amount of data is increasing day by day, there may arrise the following problems: • Processor speed: To handle very large amout of data, high speed processing is required, but as the data is growing day by day to the billions of files per entity, processor may fail to deal with that much amount of data. • Data Search: Consider an inventory size of 106 items in a store, If our application needs to search for a particular item, it needs to traverse 106 items every time, results in slowing down the search process. • Multiple requests: If thousands of users are searching the data simultaneously on a web server, then there are the chances that a very large server can be failed during that process
  • 5. ADVANTAGES OF DATA STRUCTURES • Advantages of Data Structures • Efficiency: Efficiency of a program depends upon the choice of data structures. For example: suppose, we have some data and we need to perform the search for a perticular record. In that case, if we organize our data in an array, we will have to search sequentially element by element. hence, using array may not be very efficient here. There are better data structures which can make the search process efficient like ordered array, binary search tree or hash tables. • Reusability: Data structures are reusable, i.e. once we have implemented a particular data structure, we can use it at any other place. Implementation of data structures can be compiled into libraries which can be used by different clients. • Abstraction: Data structure is specified by the ADT which provides a level of abstraction. The client program uses the data structure through interface only, without getting into the implementation details.
  • 7.  Linear Data Structures: A data structure is called linear if all of its elements are arranged in the linear order. In linear data structures, the elements are stored in non-hierarchical way where each element has the successors and predecessors except the first and last element.  Types of Linear Data Structures are given below:  Arrays: An array is a collection of similar type of data items and each data item is called an element of the array. The data type of the element may be any valid data type like char, int, float or double. The elements of array share the same variable name but each one carries a different index number known as subscript. The array can be one dimensional, two dimensional or multidimensional. The individual elements of the array age are: age[0], age[1], age[2], age[3],......... age[98], age[99].  Linked List: Linked list is a linear data structure which is used to maintain a list in the memory. It can be seen as the collection of nodes stored at non-contiguous memory locations. Each node of the list contains a pointer to its adjacent node.  Stack: Stack is a linear list in which insertion and deletions are allowed only at one end, called top.  A stack is an abstract data type (ADT), can be implemented in most of the programming languages. It is named as stack because it behaves like a real-world stack, for example: - piles of plates or deck of cards etc.  Queue: Queue is a linear list in which elements can be inserted only at one end called rear and deleted only at the other end called front. LINEAR DATA STRUCTURES
  • 8. Non Linear Data Structures: This data structure does not form a sequence i.e. each item or element is connected with two or more other items in a non-linear arrangement. The data elements are not arranged in sequential structure. NON LINEAR DATA STRUCTURES Types of Non Linear Data Structures are given below: Trees: Trees are multilevel data structures with a hierarchical relationship among its elements known as nodes. The bottommost nodes in the herierchy are called leaf node while the topmost node is called root node. Each node contains pointers to point adjacent nodes. Tree data structure is based on the parent-child relationship among the nodes. Each node in the tree can have more than one children except the leaf nodes whereas each node can have atmost one parent except the root node. Trees can be classfied into many categories which will be discussed later in this tutorial. Graphs: Graphs can be defined as the pictorial representation of the set of elements (represented by vertices) connected by the links known as edges. A graph is different from tree in the sense that a graph can have cycle while the tree can not have the one.
  • 9. OPERATIONS ON DATA STRUCTURE 1) Traversing: Every data structure contains the set of data elements. Traversing the data structure means visiting each element of the data structure in order to perform some specific operation like searching or sorting. Example: If we need to calculate the average of the marks obtained by a student in 6 different subject, we need to traverse the complete array of marks and calculate the total sum, then we will devide that sum by the number of subjects i.e. 6, in order to find the average. 2) Insertion: Insertion can be defined as the process of adding the elements to the data structure at any location. If the size of data structure is n then we can only insert n-1 data elements into it. 3) Deletion:The process of removing an element from the data structure is called Deletion. We can delete an element from the data structure at any random location. If we try to delete an element from an empty data structure then underflow occurs.
  • 10. 4) Searching: The process of finding the location of an element within the data structure is called Searching. There are two algorithms to perform searching, Linear Search and Binary Search. We will discuss each one of them later in this tutorial. 5) Sorting: The process of arranging the data structure in a specific order is known as Sorting. There are many algorithms that can be used to perform sorting, for example, insertion sort, selection sort, bubble sort, etc. 6) Merging: When two lists List A and List B of size M and N respectively, of similar type of elements, clubbed or joined to produce the third list, List C of size (M+N), then this process is called merging
  • 11. ALGORITHMS The word Algorithm means “a process or set of rules to be followed in calculations or other problem- solving operations”. Therefore Algorithm refers to a set of rules/instructions that step-by-step define how a work is to be executed upon in order to get the expected results. It can be understood by taking an example of cooking a new recipe. To cook a new recipe, one reads the instructions and steps and execute them one by one, in the given sequence. The result thus obtained is the new dish cooked perfectly. Similarly, algorithms help to do a task in programming to get the expected output. The Algorithm designed are language-independent, i.e. they are just plain instructions that can be implemented in any language, and yet the output will be the same, as expected.
  • 15. Best case = fastest time to complete, with optimal inputs chosen. For example, the best case for a sorting algorithm would be data that's already sorted. Worst case = slowest time to complete, with pessimal inputs, are chosen. For example, the worst case for a sorting algorithm might be data that are sorted in reverse order (but it depends on the particular algorithm). Average case = arithmetic mean. Run the algorithm many times, using many different inputs of size n that come from some distribution that generates these inputs (in the simplest case, all the possible inputs are equally likely), compute the total running time (by adding the individual times), and divide by the number of trials. You may also need to normalize the results based on the size of the input sets.
  • 16. ASYMPTOTIC NOTATIONS Asymptotic notations are the mathematical notations used to describe the running time of an algorithm when the input tends towards a particular value or a limiting value. For example: In bubble sort, when the input array is already sorted, the time taken by the algorithm is linear i.e. the best case. But, when the input array is in reverse condition, the algorithm takes the maximum time (quadratic) to sort the elements i.e. the worst case. When the input array is neither sorted nor in reverse order, then it takes average time. These durations are denoted using asymptotic notations. There are mainly three asymptotic notations: • Big-O notation • Omega notation • Theta notation
  • 17. Mixed Notation: Mixed notation consist of two or more type of notation. It is a mixture of letter and number, i.e. Arabic numeral and Roman letter (0-9) + (A-Z). it found in UDC, LC, CC, BC & SC scheme. For example: LCq- Science QC- Physic QC1- Periodicals.
  • 18. TYPES OF NOTATIONS TYPES OF NOTATIONS BIG Oh (O) NOTATION S SMALL Oh (o) NOTATION S BIG OMEGA NOTATION SMALL OMEGA (ω) THETA (θ) NOTATION S
  • 19. BIG OH (O) NOTATIONS Big-Oh (O) notation gives an upper bound for a function f(n) to within a constant factor. We write f(n) = O(g(n)), If there are positive constants n0 and c such that, to the right of n0 the f(n) always lies on or below c*g(n). O(g(n)) = { f(n) : There exist positive constant c and n0 such that 0 ≤ f(n) ≤ c g(n), for all n ≤ n0}
  • 20. SMALL OH (O) NOTATIONS Small-o, commonly written as o, is an Asymptotic Notation to denote the upper bound (that is not asymptotically tight) on the growth rate of runtime of an algorithm. f(n) is o(g(n)), if for all real constants c (c > 0) and n0 (n0 > 0), f(n) is < c g(n) for every input size n (n > n0). The definitions of O-notation and o-notation are similar. The main difference is that in f(n) = O(g(n)), the bound f(n) <= g(n) holds for some constant c > 0, but in f(n) = o(g(n)), the bound f(n) < c g(n) holds for all constants c > 0.
  • 21. BIG OMEGA (Ω) NOTATIONS Big-Omega (Ω) notation gives a lower bound for a function f(n) to within a constant factor. We write f(n) = Ω(g(n)), If there are positive constants n0 and c such that, to the right of n0 the f(n) always lies on or above c*g(n). Ω(g(n)) = { f(n) : There exist positive constant c and n0 such that 0 ≤ c g(n) ≤ f(n), for all n ≤ n0}
  • 22. SMALL OMEGA (ꞷ) NOTATION Let f(n) and g(n) be functions that map positive integers to positive real numbers. We say that f(n) is ω(g(n)) (or f(n) ∈ ω(g(n))) if for any real constant c > 0, there exists an integer constant n0 ≥ 1 such that f(n) > c * g(n) ≥ 0 for every integer n ≥ n0. f(n) has a higher growth rate than g(n) so main difference between Big Omega (Ω) and little omega (ω) lies in their definitions.In the case of Big Omega f(n)=Ω(g(n)) and the bound is 0<=cg(n)<=f(n), but in case of little omega, it is true for 0<=c*g(n)<f(n). The relationship between Big Omega (Ω) and Little Omega (ω) is similar to that of Big-Ο and Little o except that now we are looking at the lower bounds. Little Omega (ω) is a rough estimate of the order of the growth whereas Big Omega (Ω) may represent exact order of growth. We use ω notation to denote a lower bound that is not asymptotically tight. And, f(n) ∈ ω(g(n)) if and only if g(n) ∈ ο((f(n)).
  • 23. In mathematical relation, if f(n) ∈ ω(g(n)) then, lim f(n)/g(n) = ∞ n→∞ Example: Prove that 4n + 6 ∈ ω(1); the little omega(ο) running time can be proven by applying limit formula given below. if lim f(n)/g(n) = ∞ then functions f(n) is ω(g(n)) n→∞ here,we have functions f(n)=4n+6 and g(n)=1 lim (4n+6)/(1) = ∞ n→∞ and,also for any c we can get n0 for this inequality 0 <= c*g(n) < f(n), 0 <= c*1 < 4n+6 Hence proved.
  • 24. ARRAY An array is defined as the collection of similar type of data items stored at contiguous memory locations. Arrays are the derived data type in C programming language which can store the primitive type of data such as int, char, double, float, etc. It also has the capability to store the collection of derived data types, such as pointers, structure, etc. The array is the simplest data structure where each data element can be randomly accessed by using its index number. C array is beneficial if you have to store similar elements. For example, if we want to store the marks of a student in 6 subjects, then we don't need to define different variables for the marks in the different subject. Instead of that, we can define an array which can store the marks in each subject at the contiguous memory locations. By using the array, we can access the elements easily. Only a few lines of code are required to access the elements of the array.
  • 25. ONE DIMENSIONAL ARRAY One dimensional array is an array that has only one subscript specification that is needed to specify a particular element of an array. A one-dimensional array is a structured collection of components (often called array elements) that can be accessed individually by specifying the position of a component with a single index value. Syntax: data-type arr_name[array_size]; Rules for Declaring One Dimensional Array An array variable must be declared before being used in a program. The declaration must have a data type(int, float, char, double, etc.), variable name, and subscript. The subscript represents the size of the array. If the size is declared as 10, programmers can store 10 elements. An array index always starts from 0. For example, if an array variable is declared as s[10], then it ranges from 0 to 9. Each array element stored in a separate memory location.
  • 26. OPERATION OF 1D ARRAY Following are the basic operations supported by an array.  Traverse − print all the array elements one by one.  Insertion − Adds an element at the given index.  Deletion − Deletes an element at the given index.  Search − Searches an element using the given index or by the value.  Update − Updates an element at the given index.  Sorting – Arranging in descending or ascending order  Merging – concatenate two ways into third array or merge directly into third arrays where two arrays are already sorted
  • 27. TRAVERSING AN ARRAY • Traversal operation in array or simply traversing an array means, Accessing or printing each element of an array exactly once so that the data item (values) of the array can be checked or used as part of some other operation or process (This accessing and processing is sometimes called “visiting” the array). • 📝 Note: Accessing or printing of elements always takes place one by one.
  • 28. Algorithm for Traversing an Array: Step 01: Start Step 02: [Initialize counter variable. ] Set i = LB. Step 03: Repeat for i = LB to UB. Step 04: Apply process to arr[i]. Step 05: [End of loop. ] Step 06: Stop Variables used: i : Loop counter or counter variable for the for loop. arr : Array name. LB : Lower bound. UB : Upper bound.
  • 29. INSERTION OF AN ARRAY An array is a collection of items stored at contiguous memory locations. In this article, we will see how to insert an element in an array in C. Given an array arr of size n, this article tells how to insert an element x in this array arr at a specific position pos.
  • 30. Approach: Here’s how to do it. First get the element to be inserted, say x Then get the position at which this element is to be inserted, say pos Then shift the array elements from this position to one position forward, and do this for all the other elements next to pos. Insert the element x now at the position pos, as this is now empty.
  • 31. SEARCHING IN AN ARRAY Searching in data structure refers to the process of finding the required information from a collection of items stored as elements in the computer memory. These sets of items are in different forms, such as an array, linked list, graph, or tree. Another way to define searching in the data structures is by locating the desired element of specific characteristics in a collection of items. Searching Methods Searching in the data structure can be done by applying searching algorithms to check for or extract an element from any form of stored data structure. These algorithms are classified according to the type of search operation they perform, such as: Sequential search The list or array of elements is traversed sequentially while checking every component of the set.
  • 32. For example – Linear Search. Interval Search The interval search includes algorithms that are explicitly designed for searching in sorted data structures. In terms of efficiency, these algorithms are far better than linear search algorithms. Example- Logarithmic Search, Binary search.
  • 33. SORTING IN AN ARRAY Sorting refers to the operation or technique of arranging and rearranging sets of data in some specific order. A collection of records called a list where every record has one or more fields. The fields which contain a unique value for each record is termed as the key field. For example, a phone number directory can be thought of as a list where each record has three fields - 'name' of the person, 'address' of that person, and their 'phone numbers'. Being unique phone number can work as a key to locate any record in the list. Sorting is the operation performed to arrange the records of a table or list in some order according to some specific ordering criterion. Sorting is performed according to some key value of each record. The records are either sorted either numerically or alphanumerically. The records are then arranged in ascending or descending order depending on the numerical value of the key. Here is an example, where the sorting of a lists of marks obtained by a student in any particular subject of a class.
  • 34. The techniques of sorting can be divided into two categories. These are: Internal Sorting External Sorting Internal Sorting: If all the data that is to be sorted can be adjusted at a time in the main memory, the internal sorting method is being performed. External Sorting: When the data that is to be sorted cannot be accommodated in the memory at the same time and some has to be kept in auxiliary memory such as hard disk, floppy disk, magnetic tapes etc, then external sorting methods are performed. TYPES OF SORTING  Bubble Sort  Selection Sort  Merge Sort  Insertion Sort  Quick Sort  Heap Sort  Count Sort
  • 35. MERGING OF AN ARRAY Merging two arrays means combining two separate arrays into one single array. For instance, if the first array consists of 3 elements and the second array consists of 5 elements then the resulting array consists of 8 elements. This resulting array is known as a merged array. Before moving forward, if you are not familiar with the concept of the array then, do check the article on Arrays in C. We are given two sorted arrays and our task is to merge these two sorted arrays. Input: First Array: 5 4 3 2 1 Second Array: 9 8 7 6 5 Output: Merged sorted Array: 9 8 7 6 5 5 4 3 2 1
  • 37. TWO DIMENSIONAL ARRAY A one-dimensional array can be seen as data elements organised in a row. A two-dimensional array is similar to a one-dimensional array, but it can be visualised as a grid (or table) with rows and columns. For example, a nine-by-nine grid could be referenced with numbers for each row and letters for each column. A nine-by-nine, two-dimensional array could be declared with a statement such as: game [9][9] Many games use two dimensional arrays to plot the visual environment of a game. Positions in a two dimensional array are referenced like a map using horizontal and vertical reference numbers. They are sometimes called matrices.
  • 38. Declaration of two dimensional Array in C The syntax to declare the 2D array is given below. data_type array_name[rows][columns]; Consider the following example. int twodimen[4][3]; Here, 4 is the number of rows, and 3 is the number of columns Initialization of 2D Array in C In the 1D array, we don't need to specify the size of the array if the declaration and initialization are being done simultaneously. However, this will not work with 2D arrays. We will have to define at least the second dimension of the array. The two- dimensional array can be declared and defined in the following way. int arr[4][3]={{1,2,3},{2,3,4},{3,4,5},{4,5,6}};
  • 39. LINEAR SEARCH In this article, we will discuss the Linear Search Algorithm. Searching is the process of finding some particular element in the list. If the element is present in the list, then the process is called successful, and the process returns the location of that element; otherwise, the search is called unsuccessful. Two popular search methods are Linear Search and Binary Search. So, here we will discuss the popular searching technique, i.e., Linear Search Algorithm. Linear search is also called as sequential search algorithm. It is the simplest searching algorithm. In Linear search, we simply traverse the list completely and match each element of the list with the item whose location is to be found. If the match is found, then the location of the item is returned; otherwise, the algorithm returns NULL. It is widely used to search an element from the unordered list, i.e., the list in which items are not sorted. The worst-case time complexity of linear search is O(n).
  • 40. The steps used in the implementation of Linear Search are listed as follows - First, we have to traverse the array elements using a for loop. In each iteration of for loop, compare the search element with the current array element, and - If the element matches, then return the index of the corresponding array element. If the element does not match, then move to the next element. If there is no match or the search element is not present in the given array, return -1. Now, let's see the algorithm of linear search.
  • 41. 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
  • 42. // C code to linearly search x in arr[]. If x // is present then return its location, otherwise // return -1 #include <stdio.h> int search(int arr[], int n, int x) { int i; for (i = 0; i < n; i++) if (arr[i] == x) return i; return -1; } // Driver code int main(void) { int arr[] = { 2, 3, 4, 10, 40 }; int x = 10; int n = sizeof(arr) / sizeof(arr[0]); // Function call int result = search(arr, n, x); (result == -1) ? printf("Element is not present in array") : printf("Element is present at index %d", result); return 0; }
  • 43. BINARY SEARCH • Given a sorted array arr[] of n elements, write a function to search a given element x in arr[]. • A simple approach is to do a linear search. The time complexity of the above algorithm is O(n). Another approach to perform the same task is using Binary Search. • Binary Search: Search a sorted array by repeatedly dividing the search interval in half. Begin with an interval covering the whole array. If the value of the search key is less than the item in the middle of the interval, narrow the interval to the lower half. Otherwise, narrow it to the upper half. Repeatedly check until the value is found or the interval is empty. • The idea of binary search is to use the information that the array is sorted and reduce the time complexity to O(Log n).
  • 45. // C program to implement recursive Binary Search #include <stdio.h> // A recursive binary search function. It returns // location of x in given array arr[l..r] is present, // otherwise -1 int binarySearch(int arr[], int l, int r, int x) { if (r >= l) { int mid = l + (r - l) / 2; // If the element is present at the middle // itself if (arr[mid] == x) return mid; // If element is smaller than mid, then // it can only be present in left subarray if (arr[mid] > x) return binarySearch(arr, l, mid - 1, x); // Else the element can only be present // in right subarray return binarySearch(arr, mid + 1, r, x); } // We reach here when element is not // present in array return -1; }
  • 46. int main(void) { int arr[] = { 2, 3, 4, 10, 40 }; int n = sizeof(arr) / sizeof(arr[0]); int x = 10; int result = binarySearch(arr, 0, n - 1, x); (result == -1) ? printf("Element is not present in array") : printf("Element is present at index %d", result); return 0; }
  • 47. BUBBLE SORT Bubble sort, also referred to as comparison sort, is a simple sorting algorithm that repeatedly goes through the list, compares adjacent elements and swaps them if they are in the wrong order. This is the most simplest algorithm and inefficient at the same time. Yet, it is very much necessary to learn about it as it represents the basic foundations of sorting. Although it is simple to use, it is primarily used as an educational tool because the performance of bubble sort is poor in the real world. It is not suitable for large data sets. The average and worst-case complexity of Bubble sort is O(n2), where n is a number of items. Bubble short is majorly used where - • complexity does not matter • simple and shortcode is preferred
  • 48. // Bubble sort in C #include <stdio.h> // perform the bubble sort void bubbleSort(int array[], int size) { // loop to access each array element for (int step = 0; step < size - 1; ++step) { // loop to compare array elements for (int i = 0; i < size - step - 1; ++i) { // compare two adjacent elements // change > to < to sort in descending order if (array[i] > array[i + 1]) { // swapping occurs if elements // are not in the intended order int temp = array[i]; array[i] = array[i + 1]; array[i + 1] = temp; } } } }
  • 49. // print array void printArray(int array[], int size) { for (int i = 0; i < size; ++i) { printf("%d ", array[i]); } printf("n"); } int main() { int data[] = {-2, 45, 0, 11, -9}; // find the array's length int size = sizeof(data) / sizeof(data[0]); bubbleSort(data, size); printf("Sorted Array in Ascending Order:n"); printArray(data, size); }
  • 50. SELECTION SORT The selection sort algorithm sorts an array by repeatedly finding the minimum element (considering ascending order) from unsorted part and putting it at the beginning. The algorithm maintains two subarrays in a given array. 1) The subarray which is already sorted. 2) Remaining subarray which is unsorted. In every iteration of selection sort, the minimum element (considering ascending order) from the unsorted subarray is picked and moved to the sorted subarray. Following example explains the above steps:
  • 51. arr[] = 64 25 12 22 11 // Find the minimum element in arr[0...4] // and place it at beginning 11 25 12 22 64 // Find the minimum element in arr[1...4] // and place it at beginning of arr[1...4] 11 12 25 22 64 // Find the minimum element in arr[2...4] // and place it at beginning of arr[2...4] 11 12 22 25 64 // Find the minimum element in arr[3...4] // and place it at beginning of arr[3...4] 11 12 22 25 64
  • 52. // C program for implementation of selection sort #include <stdio.h> void swap(int *xp, int *yp) { int temp = *xp; *xp = *yp; *yp = temp; } void selectionSort(int arr[], int n) { int i, j, min_idx; // One by one move boundary of unsorted subarray for (i = 0; i < n-1; i++) { // Find the minimum element in unsorted array min_idx = i; for (j = i+1; j < n; j++) if (arr[j] < arr[min_idx]) min_idx = j; // Swap the found minimum element with the first element swap(&arr[min_idx], &arr[i]); } }
  • 53. /* Function to print an array */ void printArray(int arr[], int size) { int i; for (i=0; i < size; i++) printf("%d ", arr[i]); printf("n"); } // Driver program to test above functions int main() { int arr[] = {64, 25, 12, 22, 11}; int n = sizeof(arr)/sizeof(arr[0]); selectionSort(arr, n); printf("Sorted array: n"); printArray(arr, n); return 0; }
  • 54. MERGE SORT In this article, we will discuss the merge sort Algorithm. Merge sort is the sorting technique that follows the divide and conquer approach. This article will be very helpful and interesting to students as they might face merge sort as a question in their examinations. In coding or technical interviews for software engineers, sorting algorithms are widely asked. So, it is important to discuss the topic. 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.
  • 55. /* C program for Merge Sort */ #include <stdio.h> #include <stdlib.h> // Merges two subarrays of arr[]. // First subarray is arr[l..m] // Second subarray is arr[m+1..r] void merge(int arr[], int l, int m, int r) { int i, j, k; int n1 = m - l + 1; int n2 = r - m; /* create temp arrays */ int L[n1], R[n2]; /* Copy data to temp arrays L[] and R[] */ for (i = 0; i < n1; i++) L[i] = arr[l + i]; for (j = 0; j < n2; j++) R[j] = arr[m + 1 + j]; /* Merge the temp arrays back into arr[l..r]*/ i = 0; // Initial index of first subarray j = 0; // Initial index of second subarray k = l; // Initial index of merged subarray while (i < n1 && j < n2) { if (L[i] <= R[j]) { arr[k] = L[i]; i++; }
  • 56. else { arr[k] = R[j]; j++; } k++; } /* Copy the remaining elements of L[], if there are any */ while (i < n1) { arr[k] = L[i]; i++; k++; } /* Copy the remaining elements of R[], if there are any */ while (j < n2) { arr[k] = R[j]; j++; k++; } } /* l is for left index and r is right index of the sub-array of arr to be sorted */ void mergeSort(int arr[], int l, int r) {
  • 57. INSERTION SORT Insertion sort is a simple sorting algorithm that works similar to the way you sort playing cards in your hands. The array is virtually split into a sorted and an unsorted part. Values from the unsorted part are picked and placed at the correct position in the sorted part. Algorithm To sort an array of size n in ascending order: 1: Iterate from arr[1] to arr[n] over the array. 2: Compare the current element (key) to its predecessor. 3: If the key element is smaller than its predecessor, compare it to the elements before. Move the greater elements one position up to make space for the swapped element.
  • 58. Another Example: 12, 11, 13, 5, 6 Let us loop for i = 1 (second element of the array) to 4 (last element of the array) i = 1. Since 11 is smaller than 12, move 12 and insert 11 before 12 11, 12, 13, 5, 6 i = 2. 13 will remain at its position as all elements in A[0..I- 1] are smaller than 13 11, 12, 13, 5, 6 i = 3. 5 will move to the beginning and all other elements from 11 to 13 will move one position ahead of their current position. 5, 11, 12, 13, 6 i = 4. 6 will move to position after 5, and elements from 11 to 13 will move one position ahead of their current position. 5, 6, 11, 12, 13
  • 59. Time Complexity: O(n^2) Auxiliary Space: O(1) Boundary Cases: Insertion sort takes maximum time to sort if elements are sorted in reverse order. And it takes minimum time (Order of n) when elements are already sorted. Algorithmic Paradigm: Incremental Approach Sorting In Place: Yes Stable: Yes Online: Yes Uses: Insertion sort is used when number of elements is small. It can also be useful when input array is almost sorted, only few elements are misplaced in complete big array. What is Binary Insertion Sort? We can use binary search to reduce the number of comparisons in normal insertion sort. Binary Insertion Sort uses binary search to find the proper location to insert the selected item at each iteration. In normal insertion, sorting takes O(i) (at ith iteration) in worst case. We can reduce it to O(logi) by using binary search. The algorithm, as a whole, still has a running worst case running time of O(n^2) because of the series of swaps required for each insertion. Refer this for implementation. How to implement Insertion Sort for Linked List? Below is simple insertion sort algorithm for linked list.
  • 60. // C program for insertion sort #include <math.h> #include <stdio.h> void insertionSort(int arr[], int n) { int i, key, j; for (i = 1; i < n; i++) { key = arr[i]; j = i - 1; while (j >= 0 && arr[j] > key) { arr[j + 1] = arr[j]; j = j - 1; } arr[j + 1] = key; } } // A utility function to print an array of size n void printArray(int arr[], int n) { int i; for (i = 0; i < n; i++) printf("%d ", arr[i]); printf("n"); } /* Driver program to test insertion sort */ int main() { int arr[] = { 12, 11, 13, 5, 6 }; int n = sizeof(arr) / sizeof(arr[0]); insertionSort(arr, n); printArray(arr, n); return 0; }}
  • 61. QUICK SORT QuickSort •Difficulty Level : Medium •Last Updated : 25 Jan, 2022 Like Merge Sort, QuickSort is a Divide and Conquer algorithm. It picks an element as pivot and partitions the given array around the picked pivot. There are many different versions of quickSort that pick pivot in different ways. 1.Always pick first element as pivot. 2.Always pick last element as pivot (implemented below) 3.Pick a random element as pivot. 4.Pick median as pivot. The key process in quickSort is partition(). Target of partitions is, given an array and an element x of array as pivot, put x at its correct position in sorted array and put all smaller elements (smaller than x) before x, and put all greater elements (greater than x) after x. All this should be done in linear time.
  • 62. / Quick sort in C #include <stdio.h> // function to swap elements void swap(int *a, int *b) { int t = *a; *a = *b; *b = t; } // function to find the partition position int partition(int array[], int low, int high) { // select the rightmost element as pivot int pivot = array[high]; // pointer for greater element int i = (low - 1);
  • 63. // pointer for greater element int i = (low - 1); // traverse each element of the array // compare them with the pivot for (int j = low; j < high; j++) { if (array[j] <= pivot) { // if element smaller than pivot is found // swap it with the greater element pointed by i i++; // swap element at i with element at j swap(&array[i], &array[j]); } } // swap the pivot element with the greater element at i swap(&array[i + 1], &array[high]); // return the partition point return (i + 1); } void quickSort(int array[], int low, int high) { if (low < high) { // find the pivot element such that // elements smaller than pivot are on left of pivot // elements greater than pivot are on right of pivot int pi = partition(array, low, high); // recursive call on the left of pivot quickSort(array, low, pi - 1); // recursive call on the right of pivot quickSort(array, pi + 1, high);
  • 64. } } // function to print array elements void printArray(int array[], int size) { for (int i = 0; i < size; ++i) { printf("%d ", array[i]); } printf("n"); } // main function int main() { int data[] = {8, 7, 2, 1, 0, 9, 6}; int n = sizeof(data) / sizeof(data[0]); printf("Unsorted Arrayn"); printArray(data, n); // perform quicksort on data quickSort(data, 0, n - 1); printf("Sorted array in ascending order: n"); printArray(data, n); }
  • 65. COUNT SORT Counting sort is a sorting technique based on keys between a specific range. It works by counting the number of objects having distinct key values (kind of hashing). Then doing some arithmetic to calculate the position of each object in the output sequence. Let us understand it with the help of an example. For simplicity, consider the data in the range 0 to 9. Input data: 1, 4, 1, 2, 7, 5, 2 1) Take a count array to store the count of each unique object. Index: 0 1 2 3 4 5 6 7 8 9 Count: 0 2 2 0 1 1 0 1 0 0 2) Modify the count array such that each element at each index stores the sum of previous counts. Index: 0 1 2 3 4 5 6 7 8 9 Count: 0 2 4 4 5 6 6 7 7 7
  • 66. The modified count array indicates the position of each object in the output sequence. 3) Rotate the array clockwise for one time. Index: 0 1 2 3 4 5 6 7 8 9 Count: 0 0 2 4 4 5 6 6 7 7 4) Output each object from the input sequence followed by increasing its count by 1. Process the input data: 1, 4, 1, 2, 7, 5, 2. Position of 1 is 0. Put data 1 at index 0 in output. Increase count by 1 to place next data 1 at an index 1 greater than this index. Time Complexity: O(n+k) where n is the number of elements in input array and k is the range of input. Auxiliary Space: O(n+k) The problem with the previous counting sort was that we could not sort the elements if we have negative numbers in it. Because there are no negative array indices. So what we do is, we find the minimum element and we will store count of that minimum element at zero index.
  • 67. // C Program for counting sort #include <stdio.h> #include <string.h> #define RANGE 255 // The main function that sort the given string arr[] in // alphabetical order void countSort(char arr[]) { // The output character array that will have sorted arr char output[strlen(arr)]; // Create a count array to store count of individual // characters and initialize count array as 0 int count[RANGE + 1], i; memset(count, 0, sizeof(count)); // Store count of each character for (i = 0; arr[i]; ++i) ++count[arr[i]]; // Change count[i] so that count[i] now contains actual // position of this character in output array for (i = 1; i <= RANGE; ++i) count[i] += count[i - 1]; // Build the output character array for (i = 0; arr[i]; ++i) { output[count[arr[i]] - 1] = arr[i]; --count[arr[i]]; } /* For Stable algorithm for (i = sizeof(arr)-1; i>=0; --i) { output[count[arr[i]]-1] = arr[i]; --count[arr[i]]; }
  • 68. For Logic : See implementation */ // Copy the output array to arr, so that arr now // contains sorted characters for (i = 0; arr[i]; ++i) arr[i] = output[i]; } // Driver program to test above function int main() { char arr[] = "geeksforgeeks"; //"applepp"; countSort(arr); printf("Sorted character array is %sn", arr); return 0; }