Chapter4: s Data: It is a collection of raw facts that has implicit meaning. Data may be single valued like ID, or multi valued like address. Information: It is the processed data having explicit meaning. Data has to be processed to give meaning. To process, the data has to be organized. Organizing requires structuring the data. Space and time plays an important role in structuring the data. What are data structures? Data structure is a way of collecting and organizing data such that operations on the data can be performed in an effective way. Data Types Operations s Classification of data structures How are data structures classified? 1
What are primitive data structures? They are Data structures that can be operated directly by machine level instructions. Give an example for Primitive data structure. Examples are int, char float, double, pointer What are non-primitive data structures? They are Data structures that cannot be manipulated directly by machine level instructions. Mention any one non primitive data structure. Examples are Array, stacks, queues, linked lists, trees, graphs Depending on the type of relationships between the data elements, non primitive data structures can be classified as linear and nonlinear data structures. What is meant by linear data structure? They are Non primitive data structures that show relationship of logical adjacency between elements Mention any one linear data structure. Arrays, stacks, queues, linked lists What are nonlinear data structures? They are Data structures that establish relationship other than adjacency are called non primitive data structures. Give an example for nonlinear data structures. Trees, Graphs are some examples of non linear data structures. Operations on s: Mention the various operations performed on data structures. Operations on primitive data structures: CREATE DESTROY SELECT UPDATE CREATE: It reserves memory for the program element Example int x = 10; 2
This causes memory to be allocated for variable x and it allows integer value 10 to be stored. SELECT: It is frequently used to access data within a data structure. Example: cout<<a[5]; The array element a[5] is selected for printing. UPDATE: It is used to change or modify the data in the data structure. Example: int x=3; x=10; This modifies the value of x from 3 to 10 DESTROY: It is used to deallocate the memory. It is not essential operation since the memory allocated is freed automatically when the execution ends. Note!! C programming provides free () function, C++ provides destructors and Java provides a mechanism of Garbage collection to free memory. Operations on non primitive data structures What is meant by traversal? Traversal: It is the process of accessing (visiting) each element exactly once so as to perform certain operations on it. What is searching? Searching: It is the process of finding the presence of an element which satisfies one or more given conditions and displaying its position. Insertion: It is the process of adding a new element to the structure. For this the position should first be identified and only then the new element can be inserted. Deletion: It is the process of removing an element from the existing structure. What is meant by sorting? Sorting: It is the process of arranging elements in some logical order. Merging: It is the process of combining the elements in two different structures into a single structure. 3
What is an array? It is a non-primitive linear data structure that is a collection of homogeneous elements which can be accessed through a single name and occupies continuous memory location. An index or subscript is a number used to represent the size of the array or locate the position of the element in an array. Application of arrays: Arrays are used to perform matrix operations Databases use arrays to hold elements as records. They are used to implement other data structures like stacks, queues etc. Advantages of arrays Data accessing is faster: we can access any data item efficiently just by specifying the index of that item. Simple: Arrays are simple to understand and use. They can represent multiple data items of same type by using only single name. It can be used to implement other data structures like linked lists, stacks, queues, trees, graphs etc. 2D arrays can be used to represent matrices. Disadvantages of arrays The size of the array is fixed: The memory required for most of the applications often cannot be predicted while writing a program. Array items are stored contiguously: Even though the total free memory space is sufficient, this space cannot be used since arrays require contiguous storage space. Insertion and deletion operation involving arrays is tedious job: if the applications require extensive manipulation of stored data, in the sequential representation, more time is spent only in the movement of the data. Types of arrays Mention the different types of arrays. Based on the number of indices, arrays are classified into 1. One Dimensional Array 2. Two dimensional Array 3. Multi Dimensional Array 4
One Dimensional Array: It is an array in which elements are accessed using only one subscript. This subscript represents the position of the element in the array. The amount of memory occupied by the array depends on the number of subscripts and the data type of the subscripts. Syntax for Declaring One Dimensional Array data_type array_name [size]; Data_type indicates what type of data is stored in the array. It can be int, char, float, double, structure, union Size is an integer expression that specifies the number of elements in the array. If the value is n, the range of index values is 0 through n-1 and not 1 to n. Note: Data type of the Subscript should be int only. Character array terminate with a NULL character. Calculating length of array The length of the array can be calculated by L = UB-LB+1. Where LB is the lower bound which is zero by default. UB is upper bound which is the value of the subscript of the last element in the array. Example: LB=0 UB=4 10 20 30 40 50 A[0] A[1] A[2] A[3] A[4] Size of the Array L = 4 0 + 1 = 5 Representation of one dimensional array in memory Explain the memory representation of a one dimensional array. Location 0 1 2 3 4 Content 10 20 30 40 50 Address 5000 5002 5004 5006 5008 Arrays are stored in continuous memory location. However, the name of the array points to the first address called base address and not the complete array address. The address of any element of the array is calculated by Location * size of data type + base address Example: Address of A[3] = 3 * 2 + 5000 = 5006-5
Basic operations on 1-D arrays Array is a non primitive data structure hence the operations that can be performed include Traversing Searching Insertion Deletion Sorting Merging Traversing: Program to accept and display the elements of the array #include<iostream.h> #include<conio.h> class array private: int a[10], n,i; public: void input() cout<< enter the number of elements <<endl; cin>>n; cout<< enter the array elements <<endl; for(i=0;i<n; i++) cin>>a[i]; void output() cout<< elements of the array are <<endl; for(i=0;i<n;i++) cout<<a[i]<< \t ; ; void main() array a; clrscr(); a.input(); a.output(); getch(); 6
Write an algorithm for traversal in a linear array. Algorithm: Let A be the linear array, N be the size of the array, I be the variable for traversing through the array. Step1: Start Step 2: Input N Step 3: For I=0 to N-1 Do Input A[I] End of For loop Step 4: For I=0 to N-1 Do Output A[I] End of For loop Step 5: Stop only logic of the program for 3 marks Searching: The searching algorithms are important for areas like web search and other real world applications. The various search algorithms are sequential search, Binary Search, Interpolation Search, Hashing. Mention the types of searching in the array. Linear search and binary search are the search algorithms in array. Linear Search: (Sequential Search) It is the simplest search algorithm. The principle of linear search is: Start comparing the search element with every element of the array, from the beginning till the end one after the other. If the element is matched, search process is stopped and the position is retrieved. Search is unsuccessful if the position is not retrieved. Algorithm for Linear search: Let A be an array with N elements. SE be the search element. The algorithm displays the location loc where the search element is found. Initially the value of loc is -1. This value does not change if the element is not found. Step1: Start Step 2: loc= -1 Step 3: For I = 0 to N-1 If (A[I] = SE) Loc=I + 1; Go to Step 3 End of if End of for Step 4: if (loc > =0) 7
Display loc Else Display Element not found Step 5: Stop Program for Linear search #include<iostream.h> #include<conio.h> class lsearch int a[10],i,se,n,loc; public: void input() cout<<"enter the size of the array"<<endl; cin>>n; cout<<"enter the array elements"<<endl; for(i=0;i<n;i++) cin>>a[i]; cout<<"enter the search element"<<endl; cin>>se; void compute() loc=-1; for(i=0;i<n;i++) if(a[i]==se) loc=i; break; void output() if(loc>=0) cout<<"element found at "<< loc << " position"; else cout<<"element not found"; ; void main() lsearch L; 8
clrscr(); L.input(); L.compute(); L.output(); getch(); Advantages: Very simple approach Works well for small arrays. It can be used on unsorted arrays too. Disadvantages: Less efficient if the array size is large. If the elements are sorted, linear search is not efficient. Binary Search: It works on the principle of Divide and Conquer. It is best suited for sorted arrays and not suited for unsorted arrays. We compare the search element with the middle element, if it matches, then the search is successful. Otherwise the list is divided into two halves one from 0 th element to the middle element 1 and another from middle element + 1 to the last element. The searching will proceed in either of the two halves depending upon whether the element is greater or smaller than the middle element. The same procedure is repeated within each half until the element is found. Example: Elements 11 22 30 33 40 Position 0 1 2 3 4 Number of elements N=5 Search element SE = 33 1. Low=0 High =N-1 5-1=4 Mid = (low + High ) /2; = (0+4) / 2 = 2 Compare search element and mid element 33 > 30, search in the right half. 2. Low= mid +1 = 2 +1 = 3 High = 4 (No change) Mid = (3 + 4) / 2 = 7/2 = 3 (7/2 integer division hence 3 and not 3.5) 9
Search Element = mid element, search successful. So element found at position 3 Some more examples Assignment a. Search for the element 35 using binary search for the following sequence of elements 10, 20, 30, 35, 40, 45, 50, 55, 60 b. Search for 92 80,82, 84, 86, 88, 90, 92, 94, 96, 100 10
Write an algorithm to search an element in an array using binary search. Algorithm Let A be a sorted array of size N with lower bound LOW=0, Upper bound HIGH=N-1, Let MID denote location of mid element. ELE is the search element. Step 1: Start Step 2: Input N Step 3: For I=0 to N-1 Do Input A[I] [End of Step3 For loop] Step 4: Input ELE Step 5: LOW=0 Step 6: HIGH=N-1 Step 7: LOC=-1 Step 8: while (LOW<=HIGH) DO Step 9: MID=(LOW+HIGH)/2 Step 10: If(ELE =A[MID]) Then Step11: LOC=MID+1 Go To Step 15 Endif Step12:If(ELE<A[MID]) Then Step13: HIGH=MID-1 ELSE Step14:LOW=MID+1 Endif End of While Loop Step15:If(LOC>=0) Then Step16: Display ELE,"Found in location", LOC Else Step17: Display ELE, "Not Found" Endif Step18:Stop 11
Lab Program 5 #include<iostream.h> #include<conio.h> class bsearch int a[25],n,i,ele,loc; public: void input() cout<<"enter the number of elements"; cin>>n; cout<<"enter the array elements"; for( i=0;i<n;i++) cin>>a[i]; cout<<"enter the element to be searched"; cin>>ele; void compute() int low,high,mid ; loc=-1 low=0; high=n-1; while(low<=high) mid=(low+high) / 2; if(ele= =a[mid]) loc=mid+1; break; if(ele<a[mid]) high =mid-1; else low=mid+1; void output() if(loc<0) cout<< search unsuccessful ; else cout<< element found at <<loc<< position ; ; void main() bsearch b; clrscr(); b.input(); b.compute(); b.output(); getch(); 12
Insertion Adding the elements to the array is termed as insertion. When we insert an element to the array at any given position, the existing elements have to be moved one position up from the end till the given position. Write an algorithm to insert an element into the array Let A be an array of size N, I be the variable for traversing through array, ELE be the element to be added at the position POS. Step1: Start Step 2 : Input N Step 3: For I=0 to N-1 Do Input A[I] [End of Step 3 For loop] Step 4: Input ELE Step 5: Input POS Step 6: For I=N to POS Do A[I] = A[I-1] [End of Step 6 loop] Step 7: A[POS]= ELE Step 8: N=N+1 Step 9: For I=0 TO N-1 DO Display A[I] [End of Step 9 loop] Step 10: Stop 13
Lab Program 2 #include<iostream.h> #include<conio.h> #include<process.h> class insertion private: int a[10],n,i,ele,pos; public: void input() cout<<"enter size"<<endl; cin>>n; cout<<"enter elements"<<endl; for(i=0;i<n;i++) cin>>a[i]; cout<<"enter position"<<endl; cin>>pos; cout<<"enter the element"<<endl; cin>>ele; void compute() if(pos>n) cout<<"invalid"; exit(0); else for(i=n;i>pos;i--) a[i]=a[i-1]; a[pos]=ele; n++; void output() cout<<"array after insertion"<<endl; for(i=0;i<n;i++) cout<<a[i]<<endl; ; void main() insertion i; clrscr(); i.input(); i.compute(); i.output(); getch(); 14
Deletion When we delete an element from the array from any given position, elements have to be shifted one lower order position from the given position till the end. Write an algorithm to delete an element from the array Step 1: Start Step 2: Input N Step 3: For I=0 to N-1 Do Input A[I] [End of Step3 For loop] Step 4: Input ELE Step 5: Input POS Step 6: For I=POS to N-1 Do A[I] = A[I+1] [End of Step5 loop] Step 7: N=N-1 Step 8: For I=0 TO N-1 DO Display A[I] [End of Step6 loop] Step 9: Stop 15
Lab Program 2 #include<iostream.h> #include<conio.h> #include<stdlib.h> class deletion int a[10],n,i,pos; public: void input() cout<<"enter the size of the array"<<endl; cin>>n; cout<<"enter the array elements"<<endl; for(i=0;i<n;i++) cin>>a[i]; cout<<"enter the position to be deleted"<<endl; cin>>pos; void compute() if(pos>n-1) cout<<"invalid position"; getch(); exit(0); else for(i=pos;i<n;i++) a[i]=a[i+1]; n=n-1; void output() cout<<"array after deletion is "<<endl; for(i=0;i<n;i++) cout<<a[i]<<endl; ; void main() deletion d; clrscr(); d.input(); d.compute(); d.output(); getch(); 16
Sorting: It is an important concept used extensively in the field of computer science. It is the process of re arranging the elements in a specified order either ascending or descending. There are many methods of sorting like Bubble Sort, Selection Sort, etc. Insertion Sort: It is a simple Sorting algorithm which sorts the array by shifting elements one by one. It is efficient for smaller data sets, but inefficient for larger lists. Example: 17
Write an Algorithm to sort the elements using insertion sort Step1: Start Step 2: Input N Step 3: For I=0 to N-1 Do Input A[I] [End of Step 3 For loop] Step 4: For I=1 to N-1 Do J=I Step 5: While(J>=1) Step 6: If(A[J]<A[J-1]) Then Step 7: TEMP=A[J] Step 8: A[J] = A[J-1] Step 9: A[J-1]=TEMP Endif Step 10: J=J-1 End While loop End Step 4 For loop Step11: For I=0 to N-1 Do Display A[I] End of Step11 For loop Step12: Stop 18
Lab Program 4: #include<iostream.h> #include<conio.h> #include<stdlib.h> class sorting int a[10],n,i; public: void input() cout<<"enter the size of the array"<<endl; cin>>n; cout<<"enter the array elements"<<endl; for(i=0;i<n;i++) cin>>a[i]; void compute() int j,temp; for(i=1;i<n;i++) j=i; while(j>=1) if(a[j]<a[j-1]) temp=a[j]; a[j]=a[j-1]; a[j-1]=temp; j=j-1; void output() ; void main() sorting s; clrscr(); s.input(); s.compute(); s.output(); getch(); cout<<"array after sorting is"<<endl; for(i=0;i<n;i++) cout<<a[i]<<endl; 19
Two dimensional arrays A two-dimensional array is nothing more than an array of arrays. It helps to think of a two-dimensional array as a grid of rows and columns. It can be defined as an array with 2 subscripts. Declaring Two Dimensional Arrays Syntax data_type array_name [row-size] [ column-size] ; As with the single dimension array, each dimension of the array is indexed from zero to maximum size -1. The first index selects the row and the second index selects the column. A 2-dimensional array a, which contains three rows and four columns can be shown as below: But in the memory it is stored contiguously. Example an array of 3 rows and 3 columns is stored as row 0 row 1 row 2 10 20 30 40 50 60 70 80 90 [0][0] [0][1] [0][2] [1][0] [1][1] [1][2] [2][0] [2][1] [2][2] Representation of 2D arrays in memory A 2D array s elements are stored in continuous memory locations. It can be represented in memory using any of the following two ways: 1. Column-Major Order 2. Row-Major Order Row major order. In this method, elements of the array are arranged sequentially row by row. Thus elements of first row occupies first set of memory locations reserved for the array, elements of second row occupies the next set of memory and so on. 20
Consider the following example in which a two dimensional array consists of two rows and four columns stored sequentially in row major order as Column 0 Column 1 Column 2 Column 3 Row 0 10 20 30 40 Row 1 50 60 70 80 Address Representation Element Row 2000 A [0] [0] 10 2002 A [0] [1] 20 2004 A [0] [2] 30 0 2006 A [0] [3] 40 2008 A [1] [0] 50 2010 A [1] [1] 60 2012 A [1] [2] 70 1 2014 A [1] [3] 80 The location of element A[i][j] can be obtained by evaluating expression Loc (A [i,j]) = Base Address + W [M(i) + j] Where Base Address is the address of the first element of the array W is the word size, i.e. size occupied by each element N is the number of rows in the array M is the number of columns in the array. Example: if we want to calculate the address of element A[1][2] It can be calculated as Base address = 2000, W=2, N= 2, M=4, I=1, J=2 Loc (A [i,j]) = Base Address + W [M(i) + j] = 2000 + 2 *(4*1 + 2) = 2000 + 12 =2012 21
Column Major Order. In this method, elements of the array are arranged sequentially column by column. Thus elements of first column occupies first set of memory locations reserved for the array, elements of second column occupies the next set of memory and so on. Consider the following example in which a two dimensional array consists of two rows and four columns stored sequentially in column major order as Column 0 Column 1 Column 2 Column 3 Row 0 10 20 30 40 Row 1 50 60 70 80 Address Representation Element Column 2000 A [0] [0] 10 0 2002 A [1] [0] 50 2004 A [0] [1] 20 1 2006 A [1] [1] 60 2008 A [0] [2] 30 2 2010 A [1] [2] 70 2012 A [0] [3] 40 3 2014 A [1] [3] 80 The location of element A[i][j] can be obtained by evaluating expression Loc (A [i,j]) = Base Address + W [N(j) + i] Where Base Address is the address of the first element of the array W is the word size, i.e. size occupied by each element N is the number of rows in the array M is the number of columns in the array. Example: if we want to calculate the address of element A[1][2] It can be calculated as Base address = 2000, W=2, N= 2, M=4, I=1, J=2 Loc (A [i,j]) = Base Address + W [N(j) + i] = 2000 + 2 *(2*2 + 1) = 2000 + 10 =2010 22
// Program to read and Print elements in column major order #include<iostream.h> #include<conio.h> class arraytwod int a[5][5], i,j,r,c; public: void input() cout<<"enter the order of the matrix"<<endl; cin>>r>>c; cout<<"enter the array elements"<<endl; for(i=0;i<r;i++) for(j=0;j<c;j++) cin>>a[i][j]; void output() cout<<"elements in column major order is"<<endl; for(i=0;i<c;i++) for(j=0;j<r;j++) cout<<a[j][i]<<endl; ; void main() clrscr(); arraytwod d; d.input(); d.output(); getch(); 23