XII CS 9 - 10-Data Structure
XII CS 9 - 10-Data Structure
CLASS-XII
SUBJECT : COMPUTER SCIENCE (083)
2017-2018
CHAPTER:07
DATA STRUCTURES(ARRAY)
A data structure is a particular way of storing and organizing data in a computer so that it can be
used efficiently.Different kinds of data structures are suited to different kinds of applications.
Types of data structure
There are two types of data structures
Linear data structure-Array,Linked list,Stack,Queue
Non-Linear data structue – Graph and Tree
Array-
An array is a group of items that can be identified as similar because they are of the same nature.
Arrays come in two flavors: one dimensional and multi-dimensional arrays. Everyone of the pictures above
represents a single dimensional array.
Declaring an Array
Like any other variable, the syntax of declaring an array is:
DataType ArrayName[dimension/order]
The array is first identified by its kind, which could be a char, an int, a float, etc; followed by its name that
follows the C++ naming rules. The name is then followed by square brackets that specify the dimension of
the array or its size.
double Angle[360]; declares an array of double-precision numbers. There are 360 of these items in
the group.
Initializing an Array
52
Just like any variable can be initialized, an array also can be initialized. To accomplish this, for a
one-dimensional array, the syntax used is:
DataType ArrayName[dimension] = { element1, element2, …, elementn};
Here are examples of declaring an initializing arrays:
int number[12] = {18, 42, 25, 12, 34, 15, 63, 72, 92, 26, 26,
12}; double distance[5] = {44.14, 720.52, 96.08, 468.78, 6.28};
Operations on Arrays
#include <iostream>
int main()
{
/ We know that we need a constant number of elements
const int max = 10;
int number[max];
/ We will calculate their sum
int sum = 0;
cout << "Please type 10 integers.\n";
for( int i = 0; i < max; i++ )
{
cout << "Number " << i + 1 << ":
"; cin >> number[i];
sum += number[i];
}
cout << "\n\nThe sum of these numbers is " << Sum << "\n\n";
return 0;
}
An array can also be returned by a function. To declare and define that a function takes an array as
argument, declare the function as you would do for any regular function and, in its parentheses,
specify that the argument is an array.Here is an example:
#include <iostream>
void DisplayTheArray(double member[5]);
int main()
{
const int numberOfItems = 5;
53
double distance[numberOfItems] = {44.14, 720.52, 96.08, 468.78,
6.28}; return 0;
}
void DisplayTheArray(double member[5])
{
for(int i = 0; i < 5; ++i)
cout << "\nDistance " << i + 1 << ": " << member[i];
cout << endl;
}
You don't have to specify the dimension of the array. This means that you can leave the square brackets
empty:
#include <iostream>
void DisplayTheArray(double
member[]); int main()
{
const int NumberOfItems = 5;
double distance[NumberOfItems] = {44.14, 720.52, 96.08, 468.78, 6.28};
return 0;
}
int main()
{
const int numberOfItems = 5;
double distance[numberOfItems] = {44.14, 720.52, 96.08, 468.78,
6.28}; cout << "Members of the array";
DisplayTheArray(distance);
return 0;
}
54
Practice :-#include <iostream>
void DisplayTheArray(double member[])
{
for(int i = 0; i < 5; ++i)
cout << "\nDistance " << i + 1 << ": " <<
member[i]; cout << endl;
}
int main()
{
const int NumberOfItems = 5;
double distance[NumberOfItems] = {44.14, 720.52, 96.08, 468.78, 6.28};
cout << "Members of the array";
DisplayTheArray(distance[3]);
return 0;
}
Searching
Linear search: Linear search or sequential search is a method for finding a particular value in a list, that
consists of checking every one of its elements, one at a time and in sequence, until the desired one is
found. function for linear search
55
#include <iostream>
int LinearSearch(int Array[], const int Size, const int ValToSearch)
{ bool NotFound = true; int i =
0;
while(i < Size && NotFound)
{
if(ValToSearch != Array[i])
i++;
else
NotFound = false;
}
if( NotFound == false )
return i;
else
return -1;
}
int main()
{
int Number[] = { 67, 278, 463, 2, 4683, 812, 236,
38 }; int Quantity = sizeof(Number) / sizeof(int);
int NumberToSearch = 0;
cout << "Enter the number to search: "; cin >>
NumberToSearch; int i = LinearSearch(Number, Quantity,
NumberToSearch);
if(i == -1)
cout << NumberToSearch << " was not found in the collection\n\n";
else
{
cout << NumberToSearch << " is at the " << i+1;
if( i == 0 )
cout<< "st position of the collection\n\n";
else if( i == 1 )
cout<< "nd position of the
collection\n\n"; else if( i == 2 )
cout<< "rd position of the collection\n\n";
else
cout<< "th position of the collection\n\n";
}
return 0;
}
Binary search
A binary search is an algorithm for locating the position of an element in a sorted array. It inspects the
middle element of the sorted list: if equal to the sought value, then the position has been found; otherwise,
the upper half or lower half is chosen for further searching based on whether the sought value is greater than
or less than the middle element. The method reduces the number of elements needed to be checked by a
factor of two each time, and finds the sought value if it exists in the list or if not determines "not present", in
logarithmic time. A binary search is a dichotomic divide and conquer search algorithm.
#include<iostream.h>
#include<conio.h>
void binsearch(int ar[],int size,int ele)
56
{ int lb=0,ub=size-1,mid; //lb=>lower bound,ub=>upper bound
for(;lb<ub;)
{
mid=(lb+ub)/2;
if(ar[mid]==ele)
{
cout<<"\n SEARCH
SUCCESSFUL"; break;
}
else
if(ar[mid]<ele)
ub=mid-1;
else
if(ar[mid]>ele)
lb=mid+1;
}
if(ub<lb)
cout<<"\n SEARCH UNSUCCESSFUL";
}
void sort(int ar[],int size) //sorts the array in ascending array using bubble sort
{
int temp;
for(int i=0;i<size;i++)
for(int j=0;j<size-i-1;j++)
if(ar[j]>ar[j+1])
{
temp=ar[j];
ar[j]=ar[j+1];
ar[j+1]=temp;
}
}
void display(int ar[],int size)
{
for(int i=0;i<size;i++)
cout<<'\n'<<ar[i];
}
void input(int ar[],int size)
{
for(int i=0;i<size;i++)
cin>>ar[i];
}
void main()
{
clrscr();
int size;
cout<<"\n ENTER THE NUMBER OF ELEMENTS REQUIRED IN THE ARRAY :";
cin>>size;
int *ar=new int(size);
cout<<"\n ENTER THE ELEMENTS OF THE ARRAY :\n";
input(ar,size); //takes the input from the array
sort(ar,size); //sorts the array in the ascending order
int ele;
cout<<"\n ENTER THE ELEMENT TO BE FOUND :\n";
57
cin>>ele;
getch();
}
Sorting
A sorting algorithm is an algorithm that puts elements of a list in a certain order
1. Insertion sort is a simple sorting algorithm, a comparison sort in which the sorted array (or list) is
built one entry at a time.
#include <iostream>
#define ELEMENTS 6
void insertion_sort(int x[],int length)
{
int key,i;
for(int j=1;j<length;j++)
{
key=x[j];
i=j-1;
while(x[i]>key && i>=0)
{
x[i+1]=x[i];
i--;
}
x[i+1]=key;
}
}
int main()
{
int A[ELEMENTS]={5,2,4,6,1,3};
int x;
cout<<"NON SORTED LIST:"<<endl;
for(x=0;x<ELEMENTS;x++)
{
cout<<A[x]<<endl;
}
insertion_sort(A,ELEMENTS);
cout<<endl<<"SORTED LIST"<<endl;
for(x=0;x<ELEMENTS;x++)
{
cout<<A[x]<<endl;
}
return 0;
}
2. Selection Sort
Selection sort is a sorting algorithm, specifically an in-place comparison sort. It has O(n2) complexity,
making it inefficient on large lists, and generally performs worse than the similar insertion sort
void SelectionSort(int A[], int length)
{
int i, j, min, minat;
for(i = 0; i<(length-1); i++)
{
58
minat = i;
min = A[i];
for(j = i+1;j < length; j++) //select the min of the rest of array
{
if(min > A[j]) //ascending order for descending reverse
{
minat = j; //the position of the min element
min = A[j];
}
}
int temp = A[i];
A[i] = A[minat]; //swap
A[minat]=temp;
}
}//end selection sort
3. Bubble Sort
Bubble sort is a simple sorting algorithm. It works by repeatedly stepping through the list to be sorted,
comparing each pair of adjacent items and swapping them if they are in the wrong order
#include <iostream>
using namespace std;
int compare(int, int);
void sort(int[], const int);
int compare(int x, int y)
{
return(x > y);
}
void sort(int table[], const int n)
{
int t;
for(int i = 0; i < n; i++)
{
for(int j = 0; j < n-1; j++)
{
if(compare(table[j], table[j+1]))
{
t=table[j];
table[j]=table[j+1];
table[j+1]=t;
}
}
}
}
int quantity;
int tab[100];
int main()
{
cout << "Input quantity: ";
cin >> quantity;
cout << "Input numbers: \n\n";
for (int i = 0; i < quantity; i++)
59
{
int x = i;
cout << "#" << ++x << ": ";
cin >> tab[i];
}
cout << "\nBefore sorting: ";
for (int i = 0; i < quantity; i++)
{
cout << tab[i] << " ";
}
)
c ;
o for
u (int
t i=
0; i
< <
< qu
ant
" ity;
\ i+
n +)
A {
f c
t o
e u
r t
s <
o <
r
t t
i a
n b
g [
: i
]
"
; <
<
s
o "
r
t "
( ;
t }
a ret
b urn
, 0;}
q Country\Data Map Flag Area (sq km) Population
u
a United States 9,629,091 272,639,608
n
t
i Cameroon 475,440 15,456,092
t
y
Guatemala
Italy
Oman
Two-
int Dimen
sional
numberOfStudents
Arrays
PerClass[12][50];
A 2-
dime
nsio
nal
array
is an
array
of
array
s. In
other
word
s, it
is an
array
wher
e
each
mem
ber
of
the
array
is
also
an
array
.
Con
sider
the
belo
w
table
Declar
ing
and
Initiali
zing a
2-
Dimen
sional
Array
Like the above closing
table, a 2- square
dimensional array bracke
is made rows and ts.
columns. To Here is
declare it, use an
double pair of a examp
opening and le:
Based on this, when
initializing a 2-dimensional
array, make sure you
provide a number of
values that is less than or
equal to the number of
members.
Here is an example:
double distance[2][4] =
{44.14, 720.52, 96.08,
468.78, 6.28, 68.04, 364.55,
6234.12};
Processing a 2-
Dimensional Array
#
i
n
c
l
u
d
e
<
i
o
s
t
r
e
a
m
>
i
n
t
m
a
i
n
(
)
{
double distance[]
[4] = {
{ 44.14, 720.52, 96.08, 468.78 },
{ 6.28, 68.04, 364.55, 6234.12 }
};
STACKS
Stacks are commonly used Data Structures while writing code. It's concept is really simple which
makes it even simpler to write it in code. Consider this situation. There are a pile of 5 Books on a Table. You
want to add one book to the pile. What do you do? You simply add the book on the TOP of the pile. What if
you want the third book from the new 6 book pile? You then lift each book one by one from the TOP until the
third book reaches the top. Then you take the third book and replace all the others back into the pile by
adding them from the TOP.
#include <iostream>
#define MAX 10 // MAXIMUM STACK CONTENT
class stack
{
private:
int arr[MAX]; // Contains all the Data
int top; //Contains location of Topmost Data pushed onto Stack
public:
stack() //Constructor
{
top=-1; //Sets the Top Location to -1 indicating an empty stack
}
void push(int a) // Push ie. Add Value Function
{
top++; // increment to by 1
if(top<MAX)
{
arr[top]=a; //If Stack is Vacant store Value in Array
}
else
{
cout<<"STACK FULL!!"<<endl;
top--;
}
}
int pop() // Delete Item. Returns the deleted item
{if(top==-1)
{
cout<<"STACK IS
EMPTY!!!"<<endl; return NULL;
}
else
{ int data=arr[top]; //Set Topmost Value in data
arr[top]=NULL; //Set Original Location to NULL
top--; // Decrement top by 1
return data; // Return deleted item
}
61
}
};
int main()
{
stack a;
a.push(3);
cout<<"3 is Pushed\n";
a.push(10);
cout<<"10 is
Pushed\n"; a.push(1);
cout<<"1 is Pushed\n\n";
cout<<a.pop()<<" is Popped\n";
cout<<a.pop()<<" is Popped\n";
cout<<a.pop()<<" is Popped\n";
return 0;
}
Output:
3 is Pushed
10 is Pushed
1 is Pushed
1 is Popped
10 is Popped
3 is Popped
Clearly we can see that the last data pushed is the first one to be popped out.That's why a Stack is also
known as a LIFO Data Structure which stands for "LastIn,First Out" and I guess you know why.
Let us see how we implemented the stack. We first created a variable called top that points to the top of the
stack. It is initialised to -1 to indicate that the stack is empty. As Data is entered, the value in top increments
itself and data is stored into an array arr. Now there's one drawback to this Data Structure. Here we state the
Maximum number of elements as 10. What if we need more than 10 Data Elements? In that case we
combine a Stack along with a Linked List which will be explained later.
1. Array implementation
The array implementation aims to create an array where the first element (usually at the zero-offset) is the
bottom. That is, array[0] is the first element pushed onto the stack and the last element popped off. The
program must keep track of the size, or the length of the stack. The stack itself can therefore be effectively
implemented as a two-element structure in C:
typedef struct
{ int size;
int items[STACKSIZE];
} STACK;
The push() operation is used both to initialize the stack, and to store values to it. It is responsible for inserting
(copying) the value into the ps->items[] array and for incrementing the element counter (ps->size). In a
responsible C implementation, it is also necessary to check whether the array is already full to prevent an
overrun.
void push(STACK *ps, int x)
{
if (ps->size == STACKSIZE)
{ cout<<"Error: stack
overflow\n"; abort();
} else
ps->items[ps->size++] = x;
62
}
The pop() operation is responsible for removing a value from the stack, and decrementing the value of ps-
>size. A responsible C implementation will also need to check that the array is not already empty.
int pop(STACK *ps)
{
if (ps->size == 0){
cout<<"Error: stack
underflow\n"; abort();
} else
return ps->items[--ps->size];
}
if (node == NULL){
cout<<"Error: no space available for node\n";
abort();
} else { /* initialize node */ node->data = value;
63
Infix, Postfix and Prefix
Infix notation: X + Y
Operators are written in-between their operands. This is the usual way we write expressions. An
expression such as A * ( B + C ) / D is usually taken to mean something like: "First add B and C
together, then multiply the result by A, then divide by D to give the final answer." Infix notation needs
extra information to make the order of evaluation of the operators clear: rules built into the language
about operator precedence and associativity, and brackets ( ) to allow users to override these rules.
Postfix notation (also known as "Reverse Polish notation"): X Y +
Operators are written after their operands. The infix expression given above is equivalent to
A B C + * D /. The order of evaluation of operators is always left-to-right, and brackets cannot be used
to change this order. Because the "+" is to the left of the "*" in the example above, the addition must
be performed before the multiplication. Operators act on values immediately to the left of them.
Operators are written before their operands. The expressions given above are equivalent to
/ * A + B C D. As for Postfix, operators are evaluated left-to-right and brackets are superfluous.
Operators act on the two nearest values on the right. I have again added (totally unnecessary)
brackets to make this clear:
(/ (* A (+ B C) ) D)
Examples:
Example-1
64
QUEUES
There's a huge crowd at your local grocery store. There are too many people trying to buy their
respective items and the Shopkeeper doesnt know from where to start. Everyone wants their job done
quickly and the shopkeeper needs an efficient method to solve this problem. What does he do? He
introduces a Queue System based on the First Come, First Serve System. The Last Person trying to
buy an item stands behind the last person at the END of the queue. The Shopkeeper however is present at
the FRONT end of the queue. He gives the item to the person in FRONT of the queue and after the
transaction is done, the person in FRONT of the Queue Leaves. Then the person second in queue becomes
the First person in the Queue.
65
/* QUEUE IMPLEMENTATION */
#include <iostream>
#define MAX 5 // MAXIMUM CONTENTS IN QUEUE
class queue
{
private:
int t[MAX];
int al; // Addition End
int dl; // Deletion End
66
public:
queue()
{
dl=-1;
al=-1;
}
void del()
{
int tmp;
if(dl==-1)
{
cout<<"Queue is Empty";
}
else
{
for(int j=0;j<=al;j++)
{
if((j+1)<=al)
{
tmp=t[j+1];
t[j]=tmp;
}
else
{
al--;
if(al==-1)
dl=-1;
else
dl=0;
}
}
}
}
void add(int item)
{
if(dl==-1 && al==-1)
{
dl++;
al++;
}
else
{
al++;
if(al==MAX)
{
cout<<"Queue is Full\n";
al--;
return;
}
}
t[al]=item;
67
void display()
{
if(dl!=-1)
{
for(int i=0;i<=al;i++)
cout<<t[i]<<" ";
}
else
cout<<"EMPTY";
}
};
int main()
{
queue a;
int data[5]={32,23,45,99,24};
for(int i=0;i<5;i++)
{
a.add(data[i]);
cout<<"Addition Number : "<<(i+1)<<" : ";
a.display();
cout<<endl;
}
cout<<endl;
cout<<"Queue after adding Elements: ";
a.display();
cout<<endl<<endl;
for(i=0;i<5;i++)
{
a.del();
cout<<"Deletion Number : "<<(i+1)<<" : ";
a.display();
cout<<endl;
}
return 0;
}
OUTPUT:
Queue before adding Elements: EMPTY
Addition Number : 1 : 32
Addition Number : 2 : 32 23
Addition Number : 3 : 32 23 45
Addition Number : 4 : 32 23 45 99
Addition Number : 5 : 32 23 45 99 24
Deletion Number : 1 : 23 45 99 24
68
Deletion Number : 2 : 45 99 24
Deletion Number : 3 : 99 24
Deletion Number : 4 : 24
Deletion Number : 5 : EMPTY
As you can clearly see through the output of this program that addition is always done at the
end of the queue while deletion is done from the front end of the queue