Data Structure Classification
Data Structure Classification
Characteristics of an Algorithm
Not all procedures can be called an algorithm. An algorithm should have
the following characteristics −
Unambiguous − Algorithm should be clear and unambiguous. Each
of its steps (or phases), and their inputs/outputs should be clear and
must lead to only one meaning.
Input − An algorithm should have 0 or more well-defined inputs.
Output − An algorithm should have 1 or more well-defined outputs,
and should match the desired output.
Finiteness − Algorithms must terminate after a finite number of
steps.
Feasibility − Should be feasible with the available resources.
Independent − An algorithm should have step-by-step directions,
which should be independent of any programming code.
How to Write an Algorithm?
There are no well-defined standards for writing algorithms. Rather, it is
problem and resource dependent. Algorithms are never written to support
a particular programming code.
As we know that all programming languages share basic code constructs
like loops (do, for, while), flow-control (if-else), etc. These common
constructs can be used to write an algorithm.
We write algorithms in a step-by-step manner, but it is not always the
case. Algorithm writing is a process and is executed after the problem
domain is well-defined. That is, we should know the problem domain, for
which we are designing a solution.
Example
Let's try to learn algorithm-writing by using an example.
Problem − Design an algorithm to add two numbers and display the
result.
Step 1 − START
Step 2 − declare three integers a, b & c
Step 3 − define values of a & b
Step 4 − add values of a & b
Step 5 − store output of step 4 to c
Step 6 − print c
Step 7 − STOP
Algorithms tell the programmers how to code the program. Alternatively,
the algorithm can be written as −
Step 1 − START ADD
Step 2 − get values of a & b
Step 3 − c ← a + b
Step 4 − display c
Step 5 − STOP
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.
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.
If the size of data structure is n then we can only insert n-1 data
elements into it.
C Basic Commands
Following are the basic commands in C programming language:
/*_some_comments_*/ Whatever
written inside
this command
“/* */” inside
a C program, it
will not be
considered for
compilation
and execution.
Structure of a C program
After the above discussion, we can formally assess the
structure of a C program. By structure, it is meant that any
program can be written in this structure only. Writing a C
program in any other structure will hence lead to a
Compilation Error.
The structure of a C program is as follows:
1.
2. Variable Declaration: The next part of any C program is the
variable declaration. It refers to the variables that are to be
used in the function. Please note that in the C program, no
variable can be used without being declared. Also in a C
program, the variables are to be declared before any
operation in the function.
Example:
int main()
{
int a;
.
.
1.
2. Body: The body of a function in the C program, refers to the
operations that are performed in the functions. It can be
anything like manipulations, searching, sorting, printing, etc.
Example:
int main()
{
int a;
printf("%d", a);
.
.
1.
2. Return Statement: The last part of any C program is the
return statement. The return statement refers to the returning
of the values from a function. This return statement and
return value depend upon the return type of the function. For
example, if the return type is void, then there will be no
return statement. In any other case, there will be a return
statement and the return value will be of the type of the
specified return type.
Example:
int main()
{
int a;
printf("%d", a);
return 0;
}
1.
2. Writing first program:
Following is first program in C
#include <stdio.h>
int main(void)
printf("GeeksQuiz");
return 0;
}
1. Let us analyze the program line by line.
Line 1: [ #include <stdio.h> ] In a C program, all lines that
start with # are processed by a preprocessor which is a
program invoked by the compiler. In a very basic term,
the preprocessor takes a C program and produces another C
program. The produced program has no lines starting with #,
all such lines are processed by the preprocessor. In the
above example, the preprocessor copies the preprocessed
code of stdio.h to our file. The .h files are called header files
in C. These header files generally contain declarations of
functions. We need stdio.h for the function printf() used in the
program.
Line 2 [ int main(void) ] There must be a starting point from
where execution of compiled C program begins. In C, the
execution typically begins with the first line of main(). The
void written in brackets indicates that the main doesn’t take
any parameter (See this for more details). main() can be
written to take parameters also. We will be covering that in
future posts.
The int was written before main indicates return type of
main(). The value returned by main indicates the status of
program termination. See this post for more details on the
return type.
Line 3 and 6: [ { and } ] In C language, a pair of curly
brackets define scope and are mainly used in functions and
control statements like if, else, loops. All functions must start
and end with curly brackets.
Line 4 [ printf(“GeeksQuiz”); ] printf() is a standard library
function to print something on standard output. The
semicolon at the end of printf indicates line termination. In C,
a semicolon is always used to indicate end of a statement.
Line 5 [ return 0; ] The return statement returns the value
from main(). The returned value may be used by an
operating system to know the termination status of your
program. The value 0 typically means successful
termination.
Concept of Array
Definition
o Arrays are defined as the collection of similar type of data
items stored at contiguous memory locations.
o 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.
o Array is the simplest data structure where each data
element can be randomly accessed by using its index
number.
o For example, if we want to store the marks of a student in 6
subjects, then we don't need to define different variable for
the marks in different subject. instead of that, we can define
an array which can store the marks in each subject at a the
contiguous memory locations.
1. #include <stdio.h>
2. void main ()
3. {
4. int marks_1 = 56, marks_2 = 78, marks_3 = 88, marks_4 = 76,
marks_5 = 56, marks_6 = 89;
5. float avg = (marks_1 + marks_2 + marks_3 + marks_4 + mark
s_5 +marks_6) / 6 ;
6. printf(“avg”);
7. getch();
8. }
1. #include <stdio.h>
2. void main ()
3. {
4. int marks[6] = {56,78,88,76,56,89);
5. int i;
6. float avg;
7. for (i=0; i<6; i++ )
8. {
9. avg = avg + marks[i];
10. }
11. printf(avg);
12. }
Array Representation
Arrays can be declared in various ways in different languages. For
illustration, let's take C array declaration.
Arrays can be declared in various ways in different languages. For
illustration, let's take C array declaration.
Basic Operations
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.
Traverse Operation
This operation is to traverse through the elements of an array.
Example
Following program traverses and prints the elements of an array:
#include <stdio.h>
main() {
int LA[] = {1,3,5,7,8};
int item = 10, k = 3, n = 5;
int i = 0, j = n;
printf("The original array elements are :\n");
for(i = 0; i<n; i++) {
printf("LA[%d] = %d \n", i, LA[i]);
}
}
When we compile and execute the above program, it produces the
following result −
Output
The original array elements are :
LA[0] = 1
LA[1] = 3
LA[2] = 5
LA[3] = 7
LA[4] = 8
Insertion Operation
Insert operation is to insert one or more data elements into an array.
Based on the requirement, a new element can be added at the beginning,
end, or any given index of array.
Here, we see a practical implementation of insertion operation, where we
add data at the end of the array −
Example
Following is the implementation of the above algorithm −
Live Demo
#include <stdio.h>
main() {
int LA[] = {1,3,5,7,8};
int item = 10, k = 3, n = 5;
int i = 0, j = n;
printf("The original array elements are :\n");
n = n + 1;
while( j >= k) {
LA[j+1] = LA[j];
j = j - 1;
}
LA[k] = item;
Output
The original array elements are :
LA[0] = 1
LA[1] = 3
LA[2] = 5
LA[3] = 7
LA[4] = 8
The array elements after insertion :
LA[0] = 1
LA[1] = 3
LA[2] = 5
LA[3] = 10
LA[4] = 7
LA[5] = 8
For other variations of array insertion operation click here
Deletion Operation
Deletion refers to removing an existing element from the array and re-
organizing all elements of an array.
Algorithm
Consider LA is a linear array with N elements and K is a positive integer
such that K<=N. Following is the algorithm to delete an element available
at the Kth position of LA.
1. Start
2. Set J = K
3. Repeat steps 4 and 5 while J < N
4. Set LA[J] = LA[J + 1]
5. Set J = J+1
6. Set N = N-1
7. Stop
Example
Following is the implementation of the above algorithm −
Live Demo
#include <stdio.h>
void main() {
int LA[] = {1,3,5,7,8};
int k = 3, n = 5;
int i, j;
printf("The original array elements are :\n");
for(i = 0; i<n; i++) {
printf("LA[%d] = %d \n", i, LA[i]);
}
j = k;
while( j < n) {
LA[j-1] = LA[j];
j = j + 1;
}
n = n -1;
printf("The array elements after deletion :\n");
for(i = 0; i<n; i++) {
printf("LA[%d] = %d \n", i, LA[i]);
}
}
When we compile and execute the above program, it produces the
following result −
Output
The original array elements are :
LA[0] = 1
LA[1] = 3
LA[2] = 5
LA[3] = 7
LA[4] = 8
The array elements after deletion :
LA[0] = 1
LA[1] = 3
LA[2] = 7
LA[3] = 8
Search Operation
You can perform a search for an array element based on its value or its
index.
Algorithm
Consider LA is a linear array with N elements and K is a positive integer
such that K<=N. Following is the algorithm to find an element with a value
of ITEM using sequential search.
1. Start
2. Set J = 0
3. Repeat steps 4 and 5 while J < N
4. IF LA[J] is equal ITEM THEN GOTO STEP 6
5. Set J = J +1
6. PRINT J, ITEM
7. Stop
Example
Following is the implementation of the above algorithm −
Live Demo
#include <stdio.h>
void main() {
int LA[] = {1,3,5,7,8};
int item = 5, n = 5;
int i = 0, j = 0;
printf("The original array elements are :\n");
for(i = 0; i<n; i++) {
printf("LA[%d] = %d \n", i, LA[i]);
}
while( j < n){
if( LA[j] == item ) {
break;
}
j = j + 1;
}
printf("Found element %d at position %d\n", item,
j+1);
}
When we compile and execute the above program, it produces the
following result −
Output
The original array elements are :
LA[0] = 1
LA[1] = 3
LA[2] = 5
LA[3] = 7
LA[4] = 8
Found element 5 at position 3
Update Operation
Update operation refers to updating an existing element from the array at a
given index.
Algorithm
Consider LA is a linear array with N elements and K is a positive integer
such that K<=N. Following is the algorithm to update an element available
at the Kth position of LA.
1. Start
2. Set LA[K-1] = ITEM
3. Stop
Example
Following is the implementation of the above algorithm −
Live Demo
#include <stdio.h>
void main() {
int LA[] = {1,3,5,7,8};
int k = 3, n = 5, item = 10;
int i, j;
printf("The original array elements are :\n");
for(i = 0; i<n; i++) {
printf("LA[%d] = %d \n", i, LA[i]);
}
LA[k-1] = item;
Output
The original array elements are :
LA[0] = 1
LA[1] = 3
LA[2] = 5
LA[3] = 7
LA[4] = 8
The array elements after updation :
LA[0] = 1
LA[1] = 3
LA[2] = 10
LA[3] = 7
LA[4] = 8
Types of Arrays in C
In c programming language, arrays are classified into two types. They are as
follows...
We can also use the following general syntax to intialize a single dimensional array
without specifying size and with initial values...
datatype arrayName [ ] = {value1, value2, ...} ;
The array must be initialized if it is created without specifying any size. In this case,
the size of the array is decided based on the number of values initialized.
Example Code
int marks [] = { 89, 90, 76, 78, 98, 86 } ;
In the above example declaration, size of the array 'marks' is 6 and the size of the
array 'studentName' is 16. This is because in case of character array, compiler
stores one exttra character called \0 (NULL) at the end.
arrayName [ indexValue ]
Example Code
marks [2] = 99 ;
In the above statement, the third element of 'marks' array is assinged with
value '99'.
Most popular and commonly used multi dimensional array is two dimensional
array. The 2-D arrays are used to store data in the form of table. We also use 2-D
arrays to create mathematical matrices.
Example Code
int matrix_A [2][3] = {
{1, 2, 3},
{4, 5, 6}
} ;
We use the following general syntax to access the individual elements of a two-
dimensional array...
Array works with a static The Linked list works with dynamic
memory. Here static memory memory. Here, dynamic memory
means that the memory size is means that the memory size can
fixed and cannot be changed at be changed at the run time
the run time. according to our requirements.
Array elements are independent Linked list elements are dependent
of each other. on each other. As each node
contains the address of the next
node so to access the next node,
we need to access its previous
node.
Array takes more time while Linked list takes less time while
performing any operation like performing any operation like
insertion, deletion, etc. insertion, deletion, etc.
// using Array
#include<stdio.h>
int main()
int sparseMatrix[4][5] =
{0 , 0 , 3 , 0 , 4 },
{0 , 0 , 5 , 7 , 0 },
{0 , 0 , 0 , 0 , 0 },
{0 , 2 , 6 , 0 , 0 }
};
int size = 0;
if (sparseMatrix[i][j] != 0)
size++;
// sparseMatrix
int compactMatrix[3][size];
int k = 0;
for (int i = 0; i < 4; i++)
if (sparseMatrix[i][j] != 0)
compactMatrix[0][k] = i;
compactMatrix[1][k] = j;
compactMatrix[2][k] = sparseMatrix[i][j];
k++;
return 0;
Output:
0 0 1 1 3 3
2 4 2 3 1 2
3 4 5 7 2 6
#include<iostream>
class Node
public:
int row;
int col;
int data;
Node *next;
};
Node *r;
if (temp == NULL)
temp->row = row_index;
temp->col = col_index;
temp->data = x;
temp->next = NULL;
*p = temp;
else
temp = temp->next;
r = new Node();
r->row = row_index;
r->col = col_index;
r->data = x;
r->next = NULL;
temp->next = r;
ptr = ptr->next;
}
cout << endl;
ptr = start;
ptr = ptr->next;
ptr = start;
{
cout << ptr->data << " ";
ptr = ptr->next;
// Driver Code
int main()
int sparseMatrix[4][5] = { { 0 , 0 , 3 , 0 , 4 },
{ 0 , 0 , 5 , 7 , 0 },
{ 0 , 0 , 0 , 0 , 0 },
{ 0 , 2 , 6 , 0 , 0 } };
// Creating head/first node of list as NULL
if (sparseMatrix[i][j] != 0)
create_new_node(&first, i, j,
sparseMatrix[i][j]);
printList(first);
return 0;
Output:
row_position: 0 0 1 1 3 3
column_postion: 2 4 2 3 1 2
Value: 3 4 5 7 2 6
Declaration The declaration varies for The declaration varies for different
different programming programming language:
language:
1. For C++,
1. For C++, datatype variable_name[row]
datatype [column]
variable_name[row]
2. For Java,
datatype [] 2. For Java,
variable_name= new datatype [][] variable_name=
dataype[row] new dataype[row][column]
Declaration The declaration varies for The declaration varies for different
different programming programming language:
language:
3. For C++,
3. For C++,
datatype datatype variable_name[row]
variable_name[row] [column]
4. For Java, 4. For Java,
datatype [] datatype [][] variable_name=
variable_name= new new dataype[row][column]
dataype[row]
UNIT-(STACKS)
Stack is a linear data structure which follows a particular order in
which the operations are performed. The order may be LIFO(Last In
First Out) or FILO(First In Last Out).
Mainly the following three basic operations are performed in the
stack:
Push: Adds an item in the stack. If the stack is full, then it is said
to be an Overflow condition.
Pop: Removes an item from the stack. The items are popped in
the reversed order in which they are pushed. If the stack is
empty, then it is said to be an Underflow condition.
Peek or Top: Returns top element of stack.
isEmpty: Returns true if stack is empty, else false.
What is a Stack?
A Stack is a linear data structure that follows the LIFO (Last-In-
First-Out) principle. Stack has one end, whereas the Queue has
two ends (front and rear). It contains only one pointer top
pointer pointing to the topmost element of the stack. Whenever
an element is added in the stack, it is added on the top of the
stack, and the element can be deleted only from the stack. In
other words, a stack can be defined as a container in which
insertion and deletion can be done from the one end
known as the top of the stack.
Working of Stack
Stack works on the LIFO pattern. As we can observe in the below
figure there are five memory blocks in the stack; therefore, the
size of the stack is 5.
Since our stack is full as the size of the stack is 5. In the above
cases, we can observe that it goes from the top to the bottom
when we were entering the new element in the stack. The stack
gets filled up from the bottom to the top.
PUSH operation
The steps involved in the PUSH operation is given below:
POP operation
The steps involved in the POP operation is given below:
Applications of Stack
The following are the applications of the stack:
1. int main()
2. {
3. cout<<"Hello";
4. cout<<"javaTpoint";
5. }
As we know, each program has an opening and closing braces;
when the opening braces come, we push the braces in a stack,
and when the closing braces appear, we pop the opening braces
from the stack. Therefore, the net value comes out to be zero. If
any symbol is left in the stack, it means that some syntax occurs
in a program.
o Infix to postfix
o Prefix to infix
o Prefix to postfix
Postfix to infix
1. Increment the variable Top so that it can now refere to the next memory
location.
2. Add element at the position of incremented top. This is referred to as
adding new element at the top of the stack.
Stack is overflown when we try to insert an element into a completely filled stack
therefore, our main function must always avoid stack overflow condition.
Algorithm:
begin
if top = n then stack full
top = top + 1
stack (top) : = item;
end
1. begin
2. if top = 0 then stack empty;
3. item := stack(top);
4. top = top - 1;
5. end;
1. int pop ()
2. {
3. if(top == -1)
4. {
5. printf("Underflow");
6. return 0;
7. }
8. else
9. {
10. return stack[top - - ];
11. }
12. }
Algorithm :
1. Begin
2. if top = -1 then stack empty
3. item = stack[top]
4. return item
5. End
C program
1. #include <stdio.h>
2. int stack[100],i,j,choice=0,n,top=-1;
3. void push();
4. void pop();
5. void show();
6. void main ()
7. {
8.
9. printf("Enter the number of elements in the stack ");
10. scanf("%d",&n);
11. printf("*********Stack operations using array*********");
12.
13. printf("\n----------------------------------------------\n");
14. while(choice != 4)
15. {
16. printf("Chose one from the below options...\n");
17. printf("\n1.Push\n2.Pop\n3.Show\n4.Exit");
18. printf("\n Enter your choice \n");
19. scanf("%d",&choice);
20. switch(choice)
21. {
22. case 1:
23. {
24. push();
25. break;
26. }
27. case 2:
28. {
29. pop();
30. break;
31. }
32. case 3:
33. {
34. show();
35. break;
36. }
37. case 4:
38. {
39. printf("Exiting....");
40. break;
41. }
42. default:
43. {
44. printf("Please Enter valid choice ");
45. }
46. };
47. }
48. }
49.
50. void push ()
51. {
52. int val;
53. if (top == n )
54. printf("\n Overflow");
55. else
56. {
57. printf("Enter the value?");
58. scanf("%d",&val);
59. top = top +1;
60. stack[top] = val;
61. }
62. }
63.
64. void pop ()
65. {
66. if(top == -1)
67. printf("Underflow");
68. else
69. top = top -1;
70. }
71. void show()
72. {
73. for (i=top;i>=0;i--)
74. {
75. printf("%d\n",stack[i]);
76. }
77. if(top == -1)
78. {
79. printf("Stack is empty");
80. }
81. }
ADT:-
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. 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.
1. 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.
The top most node in the stack always contains null in its address
field. Lets discuss the way in which, each operation is performed
in linked list implementation of stack.
10.2M
188
void *DataPtr;
} StackNode;
typedef struct
int count;
StackNode *top;
} STACK;
K K
+ +
L + KL
- - K L+
M - K L+ M
* -* K L+ M
N -* KL+MN
+ + K L + M N*
K L + M N* -
( +( K L + M N *-
O +( KL+MN*-O
^ +(^ K L + M N* - O
P +(^ K L + M N* - O P
) + K L + M N* - O P ^
* +* K L + M N* - O P ^
W +* K L + M N* - O P ^ W
/ +/ K L + M N* - O P ^ W *
U +/ K L + M N* - O P ^W*U
/ +/ K L + M N* - O P ^W*U/
V +/ KL + MN*-OP^W*U/V
* +* KL+MN*-OP^W*U/V/
T +* KL+MN*-OP^W*U/V/T
+ + KL+MN*-OP^W*U/V/T*
KL+MN*-OP^W*U/V/T*+
Q + KL+MN*-OP^W*U/V/T*Q
KL+MN*-OP^W*U/V/T*+Q+