Docsity

Introduction to Data Structures in Computer Science, Study notes of Data Structures and Algorithms

Toggle sidebar
bg1
CLASS – XII
SUBJECT : COMP. SC.
UNIT : PROGRAMMING AND COMPUTATIONAL THINKING (PCT-2)
CHAPTER : DATA STRUCTURES
Introduction :
Data is the basic fact or entity that is utilized in calculation or manipulation. Data may be a
single value or it may be a set of values. Whether it is a single value or a group of values to be
processed must be organized in a particular fashion. This organization leads to structuring of
data. And hence we need to study the data structures.
Definition :
Data structure is representation of the logical relationship existing between individual elements
of data. In other words, a data structure is a way of organizing all data items that considers not
only the elements stored but also their relationship to each other.
We can also define it as a mathematical or logical model of particular organization of data
items.
Data structure mainly specifies organization of data, accessing methods, degree of
associativity, processing alternatives for information.
Data structures are the building blocks of a program. And hence the selection of a particular
data structure stresses on the following two things.
1.
The data structures must be rich enough in structure to reflect the relationship existing
between the data.
2.
The structure should be simple so that we can process data effectively whenever required.
Data structure affects the design of both structural and functional aspect of a program.
Algorithm + Data structure = Program
To develop a program of an algorithm, we should select an appropriate data structure for that
algorithm. Therefore algorithm and its associated data structures form a program.
Elementary Data Representation :
Elementary representation of data can be in the form of raw data, data item, data structure.
Data structure is a named group of data of different data types which is stored in a specific
way and can be processed as a single unit. A data structure has well-defined operations,
behaviours and properties.
DATA TYPE VS. DATA STRUCTURE :
DATA TYPE defines the type of values we can store and operations we can perform. For
example in int data type we cannot store decimal values, we cannot multiply two string type
values. It also specifies amount of memory it will take.
DATA STRUCTURE is physical implementation that clearly defines a way of storing,
accessing and manipulation of data stored in data structure. Every data structure has a specific
way of insertion and deletion like STACK work on LIFO i.e. all operation will take from one
end i.e. TOP where as QUEUE works on FIFO i.e. item inserted first will be removed first and
new item will always added to the end of QUEUE.
In python we will use LIST as a data structure.
pf3
pf4
pf5
pf8
pf9
pfa
pfd

Partial preview of the text

Download Introduction to Data Structures in Computer Science and more Study notes Data Structures and Algorithms in PDF only on Docsity!

CLASS – XII

SUBJECT : COMP. SC.

UNIT : PROGRAMMING AND COMPUTATIONAL THINKING (PCT-2)

CHAPTER : DATA STRUCTURES

Introduction : Data is the basic fact or entity that is utilized in calculation or manipulation. Data may be a single value or it may be a set of values. Whether it is a single value or a group of values to be processed must be organized in a particular fashion. This organization leads to structuring of data. And hence we need to study the data structures. Definition : Data structure is representation of the logical relationship existing between individual elements of data. In other words, a data structure is a way of organizing all data items that considers not only the elements stored but also their relationship to each other. We can also define it as a mathematical or logical model of particular organization of data items. Data structure mainly specifies organization of data, accessing methods, degree of associativity, processing alternatives for information. Data structures are the building blocks of a program. And hence the selection of a particular data structure stresses on the following two things.

  1. The data structures must be rich enough in structure to reflect the relationship existing between the data.
  2. The structure should be simple so that we can process data effectively whenever required. Data structure affects the design of both structural and functional aspect of a program.

Algorithm + Data structure = Program

To develop a program of an algorithm, we should select an appropriate data structure for that algorithm. Therefore algorithm and its associated data structures form a program. Elementary Data Representation : Elementary representation of data can be in the form of raw data, data item, data structure. Data structure is a named group of data of different data types which is stored in a specific way and can be processed as a single unit. A data structure has well-defined operations, behaviours and properties. DATA TYPE VS. DATA STRUCTURE : DATA TYPE defines the type of values we can store and operations we can perform. For example in int data type we cannot store decimal values, we cannot multiply two string type values. It also specifies amount of memory it will take. DATA STRUCTURE is physical implementation that clearly defines a way of storing, accessing and manipulation of data stored in data structure. Every data structure has a specific way of insertion and deletion like STACK work on LIFO i.e. all operation will take from one end i.e. TOP where as QUEUE works on FIFO i.e. item inserted first will be removed first and new item will always added to the end of QUEUE. In python we will use LIST as a data structure.

DIFFERENT DATA STRUCTURES :

The data structure can be classified into following two types: Simple Data structure : These are normally built from primitive data types like integer, float, string or Boolean. Example: Linear List or Array Complex Data structure : Simple data structure can be combined in various way to form more complex data structure. It is of two types: Linear : These are single level data structure i.e. in linear fashion to form a sequence. Example : STACK, QUEUE, LINKED LIST Non-Linear: These are multilevel data structure. Example: TREE and GRAPH. LINEAR LIST ARRAYS : It refers to a named list of finite number of n similar data elements. Each of the data elements can be accessed by its unique index/subscript position usually 0,1,2,3,….. For example if the list Stud_name contains 10 elements then first element will be Stud_name[0], second will be Stud_name[1] and so on. Array can be Single Dimensional or Multidimensional. In Python arrays are implemented through List data types as Linear List or through NumPy arrays. STACK : It allows to insert and delete items from one end only called TOP. Stack works on LIFO principle. It means items added in list will be removed first. Real life Example: Stack of Plates, Books, Bangles. Computer based examples: Undo Operation, Function Call etc. QUEUE : It allows insertion and deletion from different end i.e. insertion from REAR and deletion from FRONT. Queue works on FIFO principle i.e. item added first will be removed first. Real life example: Queue of People for ticket. Computer based example: Keyboard typing, Printer etc. LINKED LIST : It is dynamic data structure i.e. size of Linked List is not pre-known before the execution of program. It takes memory as per requirement during runtime and every item allocated dynamically will be known as NODE. NODE contains 2 parts: (1) INFO part stores the actual data to store like roll no. name, marks etc. and (2) LINK holds the address of next allocated node in memory creating chain of linked items.

LINEAR SEARCH FUNCTION :

def LSearch(Arr,Item): for i in range(len(Arr)): if Item == Arr[i]: return True return False Python Program for Linear Searching in a Linear List : def lin_search(mlist, item): n = len(mlist) for i in range(n): if item == mlist[i]: return i return None Ar = [] num = int(input("Enter how many items in List ")) for i in range(num): x = int(input("Enter value :")) Ar.append(x) mitem = int(input("Enter Value to Search :")) position = lin_search(Ar, mitem) if position != None: print("Found at position ",position+1) else: print("Not Found") BINARY SEARCH : Data must be sorted either in ascending or descending order to search using binary method. Searching starts from the middle position. To find middle position, Mid = (lower_index + higher_index) / 2 If middle value is equal to search element “SEARCH IS SUCCESSFUL” If middle value if larger than search value, searching continues towards left of middle position otherwise towards right side of middle position. [ for data arranged in ascending order else vice versa ] It takes less time compare to Linear searching. It is suitable for large list. BINARY SEARCH FUNCTION : def bin_search(mylist,item): low = 0 high = len(mylist)- 1 while(low<=high): mid = (low+high)// if mylist[mid]==item: return mid elif mylist[mid]>item: high = mid - 1 else: return - 1 low = mid + 1

Correct

Position

for 35

Elements

shifted down

from that

position

After

Insertion

Python Program for Binary Searching in a Linear List : def BSearch(mylist,item): low = 0 high = len(mylist)- 1 while(low<=high): mid = (low+high)// if mylist[mid]==item: return mid elif mylist[mid]>item: high = mid - 1 else: return - 1 low = mid + 1 Ar = [] num = int(input("Enter how many items in List ")) for i in range(num): x = int(input("Enter value :")) Ar.append(x) mitem = int(input("Enter Value to Search :")) position = bin_search(Ar, mitem) if position == - 1: print("Not Found") else: print("Found at position ",position+1) INSERTION IN A LINEAR LIST : Insertion of new item can be done by 2 ways: (i) In unsorted list we can add item directly at the end of list, (ii) For sorted array, we have to first find the position where new items is to be added, then shift all the elements from that position one place down and create place for new item and then insert the new item to that place. For example : INSERTION IN SORTED ARRAY: INSERT 35

Python Program for the deletion of an element from a Linear List : def BSearch(mylist,item): low = 0 high = len(mylist)- 1 while(low<=high): mid = (low+high)// if mylist[mid]==item: return mid elif mylist[mid]>item: high = mid - 1 else: low = mid + 1 return False myar=[2,5,12,17,23,29,38,46,49,52,57,63,68] print("\nThe Elements of the list are ") print(myar) x=int(input("\nEnter the number to delete : ")) position = BSearch(myar,x) if position: del myar[position] print("\nAfter deletion, The Elements of the list are ") print(myar) else: print("Sorry! No such element is found in the list.") TRAVERSAL OF A LINEAR LIST : It involves the processing of all elements one by one like: Printing of all items, Searching item one by one, Double each value of list etc. In nutshell, if we are accessing all elements one by one for any reason, it is traversing. Python Program to double the Linear List elements : def DoubleIt(Arr): for i in range(len(Arr)): #traversing all elements Arr[i] *= 2 Arr=[5,15,25,35,55] print("Current List :") for i in Arr: #traversing all elements print(i) DoubleIt(Arr) print("After the change, Elements of the List are :") print(Arr) SORTING A LINEAR LIST : Sorting refers to arrange the list items in Ascending or Descending order. Many Sorting algorithm which we can use for this purpose like: Bubble, Selection, Insertion, Shell, Quick, Heap, Merge etc. In Class XI, we have already studied about two sorting methods: Bubble Sort and Insertion Sort.

Logic of the Bubble Sort : n=len(alist) for i = 0 to n- 1 for j = 0 to n-i- 2 if (alist[j]>alist[j+1]) mx=alist[j] alist[j]= alist[j+1] alist[j+1] = mx Logic of the Insertion Sort : n=len(alist) for i = 1 to n- 1 k=alist[i] j=i – 1 while j>=0 and k else: return "Underflow" top=len(stk)- 1 return stk[top] Python Program for the implementation of Stack : def printmenu(): print("\nSTACK OPERATIONS") print("1. Push") print("2. Pop") print("3. Peek") print("4. Display Stack") print("5. Exit") ch=int(input("Enter your choice (1 - 5) : ")) return ch def isEmpty(stk): if stk==[]: return True else: return False def Push(stk,item): stk.append(item) top=len(stk)- 1 def Pop(stk): if isEmpty(stk): return "Underflow" else: item=stk.pop() if len(stk)==0: top=None else: top=len(stk)- 1 return item def Peek(stk): if isEmpty(stk): return "Underflow" else: top=len(stk)- 1 return stk[top] def Display(stk): if isEmpty(stk): print("Stack is Empty") else: top=len(stk)- 1 print("\t",stk[top],"<-top") for a in range(top-1, - 1, - 1): print("\t",stk[a])

main

Stack=[] top=None ch= while True: ch=printmenu() if ch==1: ans='y' while(ans=='y' or ans=='Y'): item=int(input("Enter the item : ")) Push(Stack,item) ans=input("Do you want to add more items (y/n) ") elif ch==2: Display(Stack) item=Pop(Stack) if item=="Underflow": print("Underflow! Stack is empty.") else: print("Popped item is ",item) x=input("Press any key to continue ") elif ch==3: item=Peek(Stack) if item=="Underflow": print("Underflow! Stack is empty.") else: print("Topmost item is ",item) x=input("Press any key to continue ") elif ch==4: Display(Stack) x=input("Press any key to continue ") elif ch==5: break QUEUE : else: print("Invalid Choice") Queue is a linear list which follows FIFO approach. Queue allows addition of element only at one end called REAR (end of list) & Deletion of element only from FRONT end (beginning of list). The operation of addition and deletion is known as Enqueue and Dequeue respectively. Applications of Queue are Printer Spooling, CPU Scheduling, Mail Service, Keyboard Buffering, Elevator etc. QUEUE OPERATIONS:

rear=len(Que)- 1 print("\t",Que[front],"<-front") for a in range(1, rear): print("\t",Que[a]) print("\t",Que[rear],"<-rear")

main

Queue=[] front=None ch= while True: ch=printmenu() if ch==1: ans='y' while(ans=='y' or ans=='Y'): item=int(input("Enter the item : ")) Enqueue(Queue,item) ans=input("Do you want to add more items (y/n) ") elif ch==2: Display(Queue) item=Dequeue(Queue) if item=="Underflow": print("Underflow! Queue is empty.") else: print("Dequeueped item is ",item) x=input("Press any key to continue ") elif ch==3: item=Peek(Queue) if item=="Underflow": print("Underflow! Queue is empty.") else: print("frontmost item is ",item) x=input("Press any key to continue ") elif ch==4: Display(Queue) x=input("Press any key to continue ") elif ch==5: break else: print("Invalid Choice") VARIATIONS OF QUEUE : Circular Queue : it is implemented in circular form rather than straight line. It is used in many programming language to overcome the problems of linear queue (utilization of unused position in the beginning). Dequeue (Doubly-ended queue) : it is the form of queue in which elements can be added or removed from any end but not in the middle. It is of two types: (1) Input restricted Deque : Input restricted means insertion only at one end but deletion from both end. (2) Output restricted Deque: Output restricted means deletion from one end and insertion from both end.