0% found this document useful (0 votes)
21 views29 pages

DS Unit 1

This document provides an introduction to linear data structures, explaining their definitions, classifications, and examples such as arrays, linked lists, stacks, queues, trees, and graphs. It discusses operations on data structures, the concept of Abstract Data Types (ADTs), and their advantages, emphasizing the importance of choosing the right data structure for efficient programming. The document also outlines the features of ADTs, highlighting their role in encapsulating data and operations while providing a user-friendly interface.

Uploaded by

smce.ramu
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
21 views29 pages

DS Unit 1

This document provides an introduction to linear data structures, explaining their definitions, classifications, and examples such as arrays, linked lists, stacks, queues, trees, and graphs. It discusses operations on data structures, the concept of Abstract Data Types (ADTs), and their advantages, emphasizing the importance of choosing the right data structure for efficient programming. The document also outlines the features of ADTs, highlighting their role in encapsulating data and operations while providing a user-friendly interface.

Uploaded by

smce.ramu
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 29

INTRODUCTION TO LINEAR DATA STRUCTURES

UNIT- 1
INTRODUCTION

 A data structure is a particular way of storing and organizing data in a computer so that it can be
used efficiently.
 Some common examples of data structures are arrays, linked lists, queues, stacks, binary trees,
and hash tables
 Today computer programmers do not write programs just to solve a problem but to write an
efficient program.
 When selecting a data structure to solve a problem, the following steps must be performed.
 Analysis of the problem to determine the basic operations that must be supported.
 Quantify the resource constraints for each operation.
 Select the data structure that best meets these requirements.

 The term data means a value or set of values. It specifies either the value of a variable or a constant
(e.g., marks of students, name of an employee, address of a customer, value of pi, etc.).
 A record is a collection of data items. For example, the name, address, course, and marks obtained
are individual data items. But all these data items can be grouped together to form a record.
 A file is a collection of related records. For example, if there are 60 students in a class, then there
are 60 records of the students. All these related records are stored in a file.

CLASSIFICATION OF DATA STRUCTURES:

Data structures are generally categorized into two classes: primitive and non-primitive data
structures.

1
Primitive and Non-primitive Data Structures:
Primitive data structures are the fundamental data types which are supported by a
programming language. Some basic data types are integer, real, character, and boolean. The terms ‘data
type, basic data type’, and ‘primitivedata type’ are often used interchangeably.
. Non-primitive data structures are those data structures which are created using primitive datastructures.
Examples of such data structures include linked lists, stacks, trees, and graphs.
Non-primitive data structures can further be classified into two categories: linear and non-linear
data structures.

Linear and Non-linear Structures:


 If the elements of a data structure are stored in a linear or sequential order, then it is a linear data
structure.
o Examples include arrays, linked lists, stacks, and queues.
o Linear data structures can be represented in memory in two different ways. One way is to
have to a linear relationship between elements by means of sequential memory locations.
The other way is to have a linear relationship between elements by means of links.

 If the elements of a data structure are not stored in a sequential order, then it is a non-linear data
structure.
o The relationship of adjacency is not maintained between elements of a non-linear data
structure. Examples include trees and graphs.

Arrays:
 An array is a collection of similar data elements. These data elements have the same data type.
The elements of the array are stored in consecutive memory locations and are referenced by an
index (also known as the subscript).
 In C, arrays are declared using the following syntax: datatype name[size];
Ex: int marks[10];

limitations:
o Arrays are of fixed size.
o Data elements are stored in contiguous memory locations which may not be always available.
o Insertion and deletion of elements can be problematic because of shifting of elements from their
positions.

2
Linked Lists:
 linked list is a dynamic data structure in which elements (called nodes) form a sequential list.
 In a linked list, each node is allocated space as it is added to the list. Every node in the list points
to the next node in the list.
 Every node contains the following
The value of the node or any other data that corresponds to that node
A pointer or link to the next node in the list

 The first node in the list is pointed by Head/Start/First. The last node in the list contains a NULL
pointer to indicate that it is the end or tail of the list.
Advantage: Easier to insert or delete data elements
Disadvantage: Slow search operation and requires more memory space
Stacks:
 A stack is a linear data structure in which insertion and deletion of elements are done at only one
end, which is known as the top of the stack.
 Stack is called a last-in, first-out (LIFO)
structure because the last element which is
added to the stack is the first element which
is deleted from the stack.
 Stacks can be implemented using arrays or
linked lists.
 Every stack has a variable top associated
with it. Top is used to store the address of
the topmost element of the stack.
 It is this position fromwhere the element will be added or deleted. There is another variable MAX,
which is used to store the maximum number of elements that the stack can store.
 If top = NULL, then it indicates that the stack is empty and if top = MAX–1, then the stack is full.
 A stack supports three basic operations: push, pop, and peep. The push operation adds an element
to the top of the stack. The pop operation removes the element from the top of the stack. And the
peep operation returns the value of the topmost element of the stack (without deleting it).

3
Queues:
 A Queue is a linear data structure in which insertion can be done at rear end and deletion of
elements can be dome at front end.
 A queue is a first-in, first-out (FIFO) data
structure in which the element that is
inserted first is the first one to be taken out.
 Like stacks, queues can be implemented by using either arrays or linked lists.

Insert element into the Queue:

Delete element from Queue:

 A queue is full when rear = MAX – 1, An underflow condition occurs when we try to delete an
element from a queue that is already empty. If front = NULL and rear = NULL, then there is no
element in the queue.
Trees:
 A tree is a non-linear data structure which consists of a collection of nodes arranged in a
hierarchical order.
 One of the nodes is designated as the root node, and the remaining nodes can be partitioned into
disjoint sets such that each set is a sub-tree of the root
 The simplest form of a tree is a binary tree. A binary tree
consists of a root node and left and right sub-trees, where both
sub-trees are also binary trees.
 Each node contains a data element, a left pointer which points
to the left sub-tree, and a right pointer which points to the right
sub-tree.
 The root element is the topmost node which is pointed by a
‘root’ pointer. If root = NULL then the tree is empty.

4
 Here R is the root node and T1 and T2 are the left and right subtrees of R. If T1 is non-empty,
then T1 is said to be the left successor of R. Likewise, if T2 is non-empty, then it is called the
right successor of R.
Advantage: Provides quick search, insert, and delete operations
Disadvantage: Complicated deletion algorithm
Graphs:
 A graph is a non-linear data structure which is a collection of vertices (also called nodes) and
edges that connect these vertices.
 A node in the graph may represent a city and the edges
connectingthe nodes can represent roads.
 A graph can also be used to represent a computer network
where the nodes are workstations and the edges are the network
connections.
 Graphs do not have any root node. Rather, every node in the graph can be connected with
every another node in the graph.
Advantage: Best models real-world situations
Disadvantage: Some algorithms are slow and very complex

OPERATIONS ON DATA STRUCTURES:

 This section discusses the different operations that can be performed on the various data
structurespreviously mentioned.
 Traversing It means to access each data item exactly once so that it can be processed. For
example, to print the names of all the students in a class.
 Searching It is used to find the location of one or more data items that satisfy the given
constraint. Such a data item may or may not be present in the given collection of data items.
For example, to find the names of all the students who secured 100 marks in mathematics.
 Inserting It is used to add new data items to the given list of data items. For example, to add
the details of a new student who has recently joined the course.
 Deleting It means to remove (delete) a particular data item from the given collection of data
items. For example, to delete the name of a student who has left the course.
 Sorting Data items can be arranged in some order like ascending order or descending order
depending on the type of application. For example, arranging the names of students in a class
in an alphabetical order, or calculating the top three winners by arranging the participants’
scores indescending order and then extracting the top three.
 Merging Lists of two sorted data items can be combined to form a single list of sorted data items.

5
ABSTRACT DATA TYPE:

ADTs are like user defined data types which defines operations on values using functions without
specifying what is there inside the function and how the operations are performed.

Example: Stack ADT


A stack consists of elements of some type arranged in a sequential order
Operations:
Initialize() – initializing it to be empty
Push() – insert an element into the stack
Pop() – delete an element from the stack
isEmpty() – Checks if stack is empty
isFull() – checks if stack is full

Here we will learn about ADT but before understanding what ADT is let us consider different in-built
data types that are provided to us. Data types such as int, float, double, long, etc. are considered to be
in-built data types and we can perform basic operations with them such as addition, subtraction,
division, multiplication, etc. Now there might be a situation when we need operations for our user-defined
data type which have to be defined. These operations can be defined only as and when we require them.
So, in order to simplify the process of solving problems, we can create data structures along with their
operations, and such data structures that are not in-built are known as Abstract Data Type (ADT).

Abstract Data type (ADT) is a type (or class) for objects whose behaviour is defined by a set of values and
a set of operations. The definition of ADT only mentions what operations are to be performed but not
how these operations will be implemented. It does not specify how data will be organized in memory
and what algorithms will be used for implementing the operations. It is called “abstract” because it gives
an implementation-independent view.

The process of providing only the essentials and hiding the details is known as abstraction.

The user of data type does not need to know how that data type is implemented, for example, we have
been using Primitive values like int, float, char data types only with the knowledge that these data type
can operate and be performed on without any idea of how they are implemented.

6
Why ADT?
 The program which used data structure is called a client program
 It has access to the ADT i., e interface.
 The program which implements the data structure is known as the implementation.

Advantages:
 Let say, if someone wants to use the stack in the program, then he can simply use push and pop
 operations without knowing its implementation.
 Also, if in future, the implementation of stack is changed from array to linked list, then the client
 program will work in the same way without being affected.

So, a user only needs to know what a data type can do, but not how it will be implemented. Think of ADT
as a black box which hides the inner structure and design of the data type. Now we’ll define three ADTs
namely List ADT, Stack ADT, Queue ADT.

1. List ADT

 The data is generally stored in key sequence in a list which has a head structure consisting of
 count, pointers and address of compare function needed to compare the data in the list.
 The data node contains the pointer to a data structure and a self-referential pointer which points to
 the next node in the list.
 The List ADT Functions is given below:
 get() – Return an element from the list at any given position.
 insert() – Insert an element at any position of the list.

7
 remove() – Remove the first occurrence of any element from a non-empty list.
 removeAt() – Remove the element at a specified location from a non-empty list.
 replace() – Replace an element at any position by another element.
 size() – Return the number of elements in the list.

 isEmpty() – Return true if the list is empty, otherwise return false.


 isFull() – Return true if the list is full, otherwise return false.

2. Stack ADT

 In Stack ADT Implementation instead of data being stored in each node, the pointer to data is stored.
 The program allocates memory for the data and address is passed to the stack ADT.
 The head node and the data nodes are encapsulated in the ADT. The calling function can only see
 the pointer to the stack.
 The stack head structure also contains a pointer to top and count of number of entries currently in
 stack.
 push() – Insert an element at one end of the stack called top.
 pop() – Remove and return the element at the top of the stack, if it is not empty.
 peek() – Return the element at the top of the stack without removing it, if the stack is not empty.
 size() – Return the number of elements in the stack.
 isEmpty() – Return true if the stack is empty, otherwise return false.
 isFull() – Return true if the stack is full, otherwise return false.

8
3. Queue ADT

 The queue abstract data type (ADT) follows the basic design of the stack abstract data type.
 Each node contains a void pointer to the data and the link pointer to the next element in the queue.
 The program’s responsibility is to allocate memory for storing the data.
 enqueue() – Insert an element at the end of the queue.
 dequeue() – Remove and return the first element of the queue, if the queue is not empty.
 peek() – Return the element of the queue without removing it, if the queue is not empty.
 size() – Return the number of elements in the queue.
 isEmpty() – Return true if the queue is empty, otherwise return false.
 isFull() – Return true if the queue is full, otherwise return false.

Features of ADT:
Abstract data types (ADTs) are a way of encapsulating data and operations on that data into a single unit.
Some of the key features of ADTs include:

 Abstraction: The user does not need to know the implementation of the data structure only essentials
 are provided.
 Better Conceptualization: ADT gives us a better conceptualization of the real world.
 Robust: The program is robust and has the ability to catch errors.
 Encapsulation: ADTs hide the internal details of the data and provide a public interface for users
 to interact with the data. This allows for easier maintenance and modification of the data structure.
 Data Abstraction: ADTs provide a level of abstraction from the implementation details of the data.
 Users only need to know the operations that can be performed on the data, not how those operations
 are implemented.
 Data Structure Independence: ADTs can be implemented using different data structures, such as
 arrays or linked lists, without affecting the functionality of the ADT.
 Information Hiding: ADTs can protect the integrity of the data by allowing access only to
 authorized users and operations. This helps prevent errors and misuse of the data.
 Modularity: ADTs can be combined with other ADTs to form larger, more complex data structures.
 This allows for greater flexibility and modularity in programming.

Overall, ADTs provide a powerful tool for organizing and manipulating data in a structured and efficient
manner.

Abstract data types (ADTs) have several advantages and disadvantages that should be considered when
deciding to use them in software development. Here are some of the main advantages and disadvantages of
using ADTs:

9
Advantages:
 Encapsulation: ADTs provide a way to encapsulate data and operations into a single unit, making it
 easier to manage and modify the data structure.
 Abstraction: ADTs allow users to work with data structures without having to know the
implementation details, which can simplify programming and reduce errors.
 Data Structure Independence: ADTs can be implemented using different data structures, which can
 make it easier to adapt to changing needs and requirements.
 Information Hiding: ADTs can protect the integrity of data by controlling access and preventing
unauthorized modifications.
 Modularity: ADTs can be combined with other ADTs to form more complex data structures, which
 can increase flexibility and modularity in programming.

Disadvantages:
 Overhead: Implementing ADTs can add overhead in terms of memory and processing, which can
 affect performance.
 Complexity: ADTs can be complex to implement, especially for large and complex data structures.
 Learning Curve: Using ADTs requires knowledge of their implementation and usage, which can
 take time and effort to learn.
 Limited Flexibility: Some ADTs may be limited in their functionality or may not be suitable for all
 types of data structures.
 Cost: Implementing ADTs may require additional resources and investment, which can increase the
 cost of development.

PRELIMINARIES OF ALGORITHM:

 Algorithm is step by step logical procedure for solving a problem.


 In Algorithm each step is called Instruction.
 An Algorithm is any well-defined computational procedure that take some values as inputs and
produce some values as output.
 An Algorithm is a sequence of computational steps that transform input into output.
 An Algorithm has 5 basic properties:
1. Input:An Algorithm has take ‘0’ or more number of inputs that can be supplied as externally.
2. Output: An Algorithm must produce at least one output.
3. Definiteness: Each instruction in the algorithm must be clear.
4. Finiteness: An algorithm must terminate after a finite number of steps.
5. Effectiveness: Each operation should be effective. i.e the operations must be terminate after
finite amount of time.

10
Structure of an Algorithm:
1. Algorithm is a procedure consisting of heading and body. In body part we are writing
statements and in the head part we are writing the following.
Syntax: Algorithm name_of_Algo (param1,param2, …);

2. The beginning and ending of block should be indicated by ‘{‘ and ‘}’ or ‘start’ and ‘end’
respectively.
3. Every statement in the algorithm should be end with semicolon (;).
4. Single line
comments are
written using ‘//’
as beginning of
comments.
5. The identifier
should begin
with character
and it may be
combination of
alpha numeric.
6. Assignment operator (:=) we can use as follows
Variable := expression (or) value;
7. There are other type of operators such as Boolean operators (TRUE/FALSE), logical operators
(AND,OR,NOT) and relational operators (<,>,<=,>=,…..)
8. The input and output we can write it as read and print respectively.
9. The Array index are stored with in [ ] brackets. The index of array starts from ‘0’ to ‘N-1’.
Syntax: datatype Aray_name[size];
10. The conditional statements such as if-then (or) if-then-else are written as follows.
if(condition) then statements;
if(condition) then
statements;
else
statements;

11
TIME AND SPACE COMPLEXITY:

 The efficiency of an algorithm can be computed by measuring the performance of an algorithm.


We can measure the performance of an algorithm in Two(2) ways.
1. Time Complexity
2. Space Complexity
1. Time Complexity:
 The time complexity of an algorithm is the amount of computing time required by an algorithm
to run its completion.
 There are 2 types of computing time 1. Compile time 2. Run time

 The time complexity generally computed at run time (or) execution time.
 The time complexity can be calculated in terms of frequency count.
 Frequency count is a count denoting the number of times the statement should be executed.
 The time complexity can be calculated as
Comments – 0
Assignment / return statement – 1
Conditional (or) Selection Constructs – 1

Example 1: Sum of the elements in an Array


Statements Step count/ Execution Frequency Total Steps
Algorithm Addition (A,n) 0 - 0
{ 0 - 0
//A is an array of size ‘n’ 0 - 0
Sum :=0; 1 1 1
for i:=1 to n do 1 n+1 n+1
Sum:=Sum+A[i]; 1 n n
return Sum; 1 1 1
} 0 - 0
Total 2n+3

Example 2: Subtraction of two matrices


Statements Step count/ Execution Frequency Total Steps
Algorithm Subtract (A,B,C,m,n) 0 - 0
{ 0 - 0
for i:=1 to m do 1 m+1 m+1
for j:=1 to n do 1 m(n+1) mn+m
C[i,j] := A[i,j] – B[i,j]; 1 mn mn
} 0 - 0
Total 2mn+2m+1

12
2. Space Complexity:
 Space Complexity can be defined as amount of memory (or) space required by an Algorithm to
run.
 To compute the space complexity we use 2 factors i. Constant ii. Instance characteristics.
 The space requirement S(p) can be given as S(p) = C+Sp
Where C- Constant, it denotes the space taken for input and output.
Sp – Amount of space taken by an instruction, variable and identifiers.

Example 1: Sum of three numbers


Algorithm Add(a,b,c)
{
//a,b,c are float type variables
return a+b+c;
}
 The space required for this algorithm is: Assume a,b,c are occupies 1 word size each, total size
comes to be 3.

Example 2: Sum of Array values


Algorithm Addition (A,n)
{
//A is an array of size ‘n’
Sum :=0;
for i:=1 to n do
Sum:=Sum+A[i];
return Sum;
}
 The space required for this algorithm is:
One word space for each variable then i,sum,n  3
For Array A[ ] we require the size  n
Total space complexity for this algorithm is S(p) ≥ (n+3)

What to Analyze in an algorithm:


An Algorithm can require different times to solve different problems of same size
1. Worst case: Maximum amount of time that an algorithm require to solve a problem of size ‘n’.
Normally we can take upper bound as complexity. We try to find worst case behavior.
2. Best case: Minimum amount of time that an algorithm require to solve a problem of size ‘n’.
Normally it is not much useful.
3. Average case: the average amount of time that an algorithm require to solve a problem of size ‘n’.
Some times it is difficult to find. Because we have to check all possible data organizations

13
SEARCHING:

 Searching means to find whether a particular value is present in an array or not.


 If the value is present in the array, then searching is said to be successful and the searching process
gives the location of that value in the array.
 However, if the value is not present in the array, the searching process displays an appropriate
message and in this case searching is said to be unsuccessful. 
 Searching techniques are linear search, binary search and Fibonacci Search

LINEAR SEARCH:

 Linear search is a technique which traverse the array sequentially to locate given item or search
element.
 In Linear search, we access each element of an array one by one sequentially and see whetherr it
is desired element or not. We traverse the entire list and match each element of the list with the
item whose location is to be found. If the match found then location of the item is returned
otherwise the algorithm return NULL.
 A search is successful then it will return the location of desired element

 If A search will unsuccessful if all the elements are accessed and desired element not found.
 Linear search is mostly used to search an unordered list in which the items are not sorted.

Algorithm of the Linear Search Algorithm


Step 1 - Read the search element from the user.
Step 2 - Compare the search element with the first element in the list.
Step 3 - If both are matched, then display "Given element is found!!!" and terminate the function
Step 4 - If both are not matched, then compare search element with the next element in the list.
Step 5 - Repeat steps 3 and 4 until search element is compared with last element in the list.

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

Linear Search ( Array Arr, Value a ) // Arr is the name of the array, and a is the searched element.

Step 1: Set i to 0 // i is the index of an array which starts from 0

Step 2: if i > n then go to step 7 // n is the number of elements in array

Step 3: if Arr[i] = a then go to step 6


14
Step 4: Set i to i + 1

Step 5: Go to step 2

Step 6: Print element a found at index i and go to step 8

Step 7: Print element not found

Step 8: Exit

.
Pseudocode of Linear Search Algorithm
1. Start
2. linear_search ( Array , value)

3. For each element in the array

4. If (searched element == value)

5. Return's the searched element location

6. end if

7. end for
8. end

Example:
Consider the following list of elements and the element to be searched...

15
.

16
Program:
#include <stdio.h> Output:

void main() Enter the size of an array


5
{ Enter the elements in
array
int a[10],i,element, found = 0,n; 10
printf("Enter the size of an array\n"); 20
30
scanf("%d",&n); 40
50
printf("Enter the elements in array \n"); Enter the element to be
for (i = 0; i < n; i++) searched 40
Element is found in the
{ array at index location = 3

scanf("%d",&a[i]);
}
printf("Enter the element to be searched ");
scanf("%d", &element);

/* Linear search begins */


for (i = 0; i < n ; i++)
{
if (a[i]==element)
{
printf("Element is found in the array at index location = %d",i);

found = 1;
break;
}
}
if(found==0)
{
printf("Element is not found in the array\n");
}
}

18
BINARY SEARCH:

• Binary search is the search technique which works efficiently on the sorted lists. Hence, in order
to search an element into some list by using binary search technique, we must ensure that the list
is sorted.
• Binary search follows 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 middle element is returned otherwise, we search into either of the halves depending
upon the result produced through the match.
Algorithm:
Step 1 - Read the search element from the user.
Step 2 - Find the middle element in the sorted list.
Step 3 - Compare the search element with the middle element in the sorted list.
Step 4 - If both are matched, then display "Given element is found!!!" and terminate the function.
Step 5 - If both are not matched, then check whether the search element is smaller or larger than
the middle element.
Step 6 - If the search element is smaller than middle element, repeat steps 2, 3, 4 and 5 for the left
sublist of the middle element.
Step 7 - If the search element is larger than middle element, repeat steps 2, 3, 4 and 5 for the right
sublist of the middle element.
Step 8 - Repeat the same process until we find the search element in the list or until sublist
contains only one element.
Step 9 - If that element also doesn't match with the search element, then display "Element is not
found in the list!!!" and terminate the function.
Example:

19
Example 2:

20
#include<stdio.h>
#include<conio.h>
void main()
{
int a[10],i,n,key,flag=0,low,high,mid;
clrscr();
printf("\n Enter the size of an array: ");
scanf("%d",&n);

printf("\n Enter the elements in ascending order: ");


for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
printf("\n Enter the number to be search: ");
scanf("%d",&key);
low=0;
high=n-1;
while(low<=high)
{
mid=(low+high)/2;
if(key==a[mid])
{
flag=1;
break;
}
else if(key<a[mid])
{
high=mid-1;
}
else
low=mid+1;
}
if(flag==1)
printf("\n The number is found and its position is: %d")
else
printf("\n The number is not found");
getch();
}

21
SORTINGS:

 Definition: Sorting is a technique to rearrange the list of records(elements) either in ascending


or descending order, Sorting is performed according to some key value of each record.
Categories of Sorting:
The sorting can be divided into two categories. These are:
 Internal Sorting
 External Sorting

 Internal Sorting: When all the data that is to be sorted can be accommodated at a time in the
main memory (Usually RAM). Internal sortings has five different classifications: insertion,
selection, exchanging, merging, and distribution sort
 External Sorting: When all the data that is to be sorted can’t be accommodated in the memory
(Usually RAM) at the same time and some have to be kept in auxiliary memory such as hard disk,
floppy disk, magnetic tapes etc.
Ex: Natural, Balanced, and Polyphase.

INSERTION SORT:

 In Insertion sort the list can be divided into two parts, one is sorted list and other is unsorted list.
In each pass the first element of unsorted list is transfers to sorted list by inserting it in appropriate
position or proper place.
 The similarity can be understood from the
style we arrange a deck of cards. This sort
works on the principle of inserting an 

22

 element at a particular position, hence the
name Insertion Sort.
Following are the steps involved in insertion sort:
1. We start by taking the second element of the given array, i.e. element at index 1, the key. The
key element here is the new card that we need to add to our existing sorted set of cards
2. We compare the key element with the element(s) before it, in this case, element at index 0:
o If the key element is less than the first element, we insert the key element before the first
element.
o If the key element is greater than the first element, then we insert it after the first element.
3. Then, we make the third element of the array as key and will compare it with elements to it's left
and insert it at the proper position.
4. And we go on repeating this, until the array is sorted.
Example 1:

Example 2:

23
Program:
#include<stdio.h>
int main()
{
int n,a[30],key,i,j,temp;
printf("Enter total elements:\n");
scanf("%d",&n);
printf("Enter elements:\n"); Output:
for(i=0;i<n;i++) Enter total elements:10
scanf("%d",&a[i]); Enter elements:
for(i=1;i<n;i++) 6 3 4 7 9 0 1 11 10 8
{ After sorting elements
j=i; are:
while(j>0 && a[j]<a[j-1]) 0 1 3 4 6 7 8 9 10 11
{
temp=a[j];
a[j]=a[j-1];
a[j-1]=temp;
j--;
}
}
printf("After sorting elements are:\n");
for(i=0;i<n;i++)
printf(" %d",a[i]);
return 0;
}

SELECTION SORT:

 Given a list of data to be sorted, we simply select the smallest item and place it in a sorted list.
These steps are then repeated until we have sorted all of the data.
 In first step, the smallest element is search in the list, once the smallest element is found, it is
exchanged with the element in the first position.
 Now the list is divided into two parts.
One is sorted list other is unsorted list.
Find out the smallest element in the
unsorted list and it is exchange with the
starting position of unsorted list, afterthat
it will added in to sorted list.
 This process is repeated until all the elements are sorted.
Ex: asked to sort a list on paper.

24
Algorithm:
SELECTION SORT(ARR, N)
Step 1: Repeat Steps 2 and 3 for K = 1 to N-1
Step 2: CALL SMALLEST(ARR, K, N, Loc)
Step 3: SWAP A[K] with ARR[Loc]
Step 4: EXIT

Algorithm for finding minimum element in the list.


SMALLEST (ARR, K, N, Loc)
Step 1: [INITIALIZE] SET Min = ARR[K]
Step 2: [INITIALIZE] SET Loc = K
Step 3: Repeat for J = K+1 to N
IF Min > ARR[J]
SET Min = ARR[J]
SET Loc = J
[END OF IF]
[END OF LOOP]
Step 4: RETURN Loc

Example 1:

25
Example 2: Consider the elements 23,78,45,88,32,56

Time Complexity:
Number of elements in an array is ‘N’
Number of passes required to sort is ‘N-1’
Number of comparisons in each pass is 1st pass N-1, 2nd Pass N-2 …
Time required for complete sorting is:
T(n) <= (N-1)*(N-1)
T(n) <= (N-1)2
Finally, The time complexity is O(n2).

PROGRAM:
#include <stdio.h>
int main()
{
int a[100], n, i, j, position, t;

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


scanf("%d", &n);

printf("Enter %d integers\n", n);

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


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

for (i = 0; i < (n - 1); i++) // finding minimum element (n-1) times


{
position = i;

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

26
{
if (a[position] > a[j]) OUTPUT:
position = j; Enter number of elements
} 6
if (position != i) Enter 6 integers
{ 60
t = a[i]; 30
a[i] = a[position]; 20
a[position] = t; 9
} 27
} 34
Sorted list in ascending order:
printf("Sorted list in ascending order:\n"); 9
20
for (i = 0; i < n; i++) 27
printf("%d\n", a[i]); 30
34
return 0; 60
}

BUBBLE SORT:

 Bubble Sort is also called as Exchange Sort


 In Bubble Sort, each element is compared with its adjacent element
a) If he first element is larger than the second element then the position of the elements are
interchanged.
b) Otherwise, the position of the elements are not changed.
c) The same procedure is repeated until no more elements are left for comparison.
 After the 1st pass the largest element is placed
at (N-1)th location. Given a list of n elements,
the bubble sort requires up to n – 1 passes to
sort the data.
Example 1:
 We take an unsorted array for our example.

 Bubble sort starts with very first two elements, comparing them to check which one is greater.

 In this case, value 33 is greater than 14, so it is already in sorted locations. Next, we compare 33

27
 with 27. We find that 27 is smaller than 33 and these two values must be swapped.

 Next we compare 33 and 35. We find that both are in already sorted positions.

 Then we move to the next two values, 35 and 10. We know then that 10 is smaller 35.

 We swap these values. We find that we have reached the end of the array. After one iteration, the
array should look like this −

 To be defined, we are now showing how an array should look like after each iteration. After the
second iteration, it should look like this

 Notice that after each iteration, at least one value moves at the end.

 And when there's no swap required, bubble sorts learns that an array is completely sorted.

Example 2:

28
Algorithm:
BUBBLE SORT(ARR, N)
Step 1: Read the
array elements
Step 2: i:=0;
Step 3: Repeat step 4 and
step 5 until i<n Step 4:
j:=0;
Step 5: Repeat step 6
until j<(n-1)-i Step 6:
if A[j] > A[j+1]
Swap(A[j],A[j+1])
End if
End loop 5
End loop 3
Step 7: EXIT

Time Complexity:
Number of elements in an array
is ‘N’ Number of passes
required to sort is ‘N-1’
Number of comparisons in each pass is 1st pass N-1, 2nd
Pass N-2 … Time required for complete sorting
is:
T(n) <= (N-1)*(N-1) T(n) <= (N-1)2
Finally, The time complexity
is O(n2).

29
Program:

#include<stdio.h>int main()
{
int n,temp,i,j,a[20];
printf("Enter total numbers of elements:\n");
scanf("%d", &n);
printf("Enter elements:\n");
for(i=0;i<n; i++) scanf("%d", &a[i]);
for(i=0;i<n; i++)
{
for(j=0;j<n-1;j++)
{
if(a[j]>a[j+1])
{
temp=a[j]; a[j]=a[j+1];
a[j+1]=temp;
}
}
}
printf("After sorting elements are:\n");for(i=0;i<n;i++)printf("
%d",a[i]);
return 0;
}
Output:
Enter total numbers of elements:
10Enter elements:
6438901527
After sorting elements are: 0 1 2 3 4 5 6 7 8 9

Time Complexities All the Searching & Sorting Techniques:

30

You might also like