0% found this document useful (0 votes)
15 views39 pages

DS Material

Data Structure Basics

Uploaded by

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

DS Material

Data Structure Basics

Uploaded by

KIRUTHIGA G
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
‘There are two types of searching - © Linear Search © Binary Search Both techniques are widely used to search an element in the given list. Linear Search What is a Linear Search? Linear search is a method of finding elements within a list. It is also called a sequential search. It is the simplest searching algorithm because it searches the desired element in a sequential manner. It compares each and every element with the value that we are searching for. If both are matched, the clement is found, and the algorithm retums the key's index position, Concept of Linear Search Let's understand the following steps to find the element key = 7 in the given list. Step - 1: Start the search from the first element and Check key = 7 with each element of list x. ‘ta]s[siz]e List to bo Searched for Step - 2: Ifelement is found, return the index position of the key. ob wen ‘1s Ts Step- 3: Ifelement is not found, return element is not present. 62 ae Kept Linear Search Algorithm. ‘There is list ofn elements and key value to be searched. Below is the linear search algorithm. 1. LinearSeareh(list, key) for each item in the list if item == value return its index position return -1 Python Program Let's understand the following Python implementation of the linear search algorithm. Program 1. defllinear_Search(listl, n, key): 2. 3. # Searching list! sequentially 4, fori in range(0, 5. if (ist [i] = key): 6. retumn i 7. retum-1 8. 9. 10. listl = [1.3,5,4.7,9] 1. key=7 12, 13. n= len(listl) 14, res = linear_Search(listl, n, key) 15. iffres == -1): 16. _print("Element not found") 63 17. else: 18, _print("Element found at index: ", res) Output: EERE SSD Explanation: In the above code, we have created a function limear_Search(), which takes three arguments - list], length of the list, and number to search. We defined for loop and iterate each element and compare to the key value. If element is found, return the index else return «1 which means element is not present in the list. Linear Search Complexity Time complexity of linear search algorithm - © Base Case - O(1) © Average Case = O(n) © Worst Case -O(n) Linear search algorithm is suitable for smaller list (<100) because it check every clement to get the desired number. Suppose there are 10,000 element list and desired element is available at the last position, this will consume much time by comparing with each element of the list. To get the fast result, we can use the binary search algorithm, Binary Searc! A binary search is an algorithm to find a particular element in the list. Suppose we have a list of thousand elements, and we need to get an index position of a particular element. We can find the element's index position very fast using the binary search algorithm ‘There are many searching algorithms but the binary search is most popular among them. The elements in the list must be sorted to apply the binary sea sort them first. algorithm. If elements are not sorted then Let's understand the concept of binary search. Concept of Binary Search ‘The divide and conquer approach technique is followed by the r is called itself again and again until it found an element in the list. cursive method. In this method, a function 64 A set of statements is repeated multiple times to find an element's index position in the iterative method. ‘The while loop is used for accomplish this task. Binary search is more effective than the linear search because we don’t need to search each list index. The list must be sorted to achieve the binary search algorithm, Let's have a step by step implementation of binary search. We have a sorted list of elements, and we are looking for the index position of 45, [12, 24, 32, 39, 45, 50, 54] So, we are setting two pointers in our list. One pointer is used to denote the smaller value called low and the second pointer is used to denote the highest value called high. Next, we calculate the value of the middle element in the array nid = (ow*high)2 Here, the low is 0 and the high is 7. mid = (0+7)72 mid = 3 (Integer) Now, we will compare the searched element to the mid index value. In this case, 32 is not equal to 45. So ‘we need to do further comparison to find the element. If the number we are searching equal to the mid. Then retum mid otherwise move to the further comparison. ‘The number to be search is greater than the middle number, we compare the m with the middle element of the elements on the right side of mid and set low to low = mid + 1. Otherwise, compare the nwith the middle element of the elements on the left side ofmid and set high to high = mid - 1. 65 12| 24 | 32 | 39 | 45 | 50 | 54 low high 12 | 24 | 32 | 30 | 45 | 50 | 54 | 39<45 low mid high 42| 24 | 32 | 30 | 45 | 60 | 64 | 45=45 t t iow mid high 42| 24 | 32 | 39 | 45 | 50 | 54 t t low mid high Repeat until the number that we are searching for is found. Implement a Binary Search in Python First, we implement a binary search with the iterative method. We will repeat a set of statements and iterate every item of the list. We will find the middle value until the search is complete. Let's understand the following program of the iterative method. Python Implementation # erative Binary Search Function method Python Implementation # Itretums index of n in given list] if present, H else returns «1 def binary_searchy(list1, n): low=0 high = len(list) -1 mid=0 66 while low < high # for get integer result mid = (high + low) /2 4# Check if'n is present at mid if list [mid] < n: low= mid +1 # If'm is greater, compare to the right of mid elif list! [mid] > n: high = mid - 1 # In is smaller, compared to the left of mid else: retum mid # element was not present in the list, retum -1 retum -1 4 Initial list listl = (12, 24, 32, 39, 45, 50, 54] n=45 # Function call result = binary_search(listl, n) ifresult != -1 print("Element is present at index", str(result)) else: print("Element is not present in list") 67 Output: Explanati In the above program - © We have erated a function called binary_seareh() function which takes two arguments - a list to sorted and a number to be searched. © We have declared two variables to store the lowest and highest values in the list. The low is assigned initial value to 0, high to len(listl) - 1 and mid as 0 © Next, we have declared the while loop with the condition that the lowest is equal and smaller than the highest The while loop will iterate if the number has not been found yet. © In the while loop, we find the mid value and compare the index value to the number we are searching for. If the value of the mid-index is smaller than m, we inerease the mid value by 1 and assign it to The search moves to the left side. © Otherwise, decrease the mid value and assign it to the high. The search moves to the right side. © Ifthe is equal to the mid value then return mid, © This will happen until the low is equal and smaller than the high. © If we reach at the end of the function, then the element is not present in the list. We retum -1 to the calling function, Sorting - Bubble Sort, Selection Sort, Insertion Sort, Merge Sort, Quick Sort, Bubble Sort: It is a simple sorting algorithm which sorts ‘n’ number of elements in the list by comparing the ach pair of adjacent items and swaps them if they are in wrong order. Algorithm: 1. Starting with the first element (index), compare the current element with the next element of alist. 2. If the current element is greater (>) than the next element of the list then swap them. 3. If the current element is less (<) than the next element of the list move to the next element, 4. Repeat step 1 until it correct order is framed. 68 For ex: listI=[10, 15, 4, 23, 0] so here we are comparing values again swap and again, so we use loops. Do nothing/remains same #Write a python program to arrange the elements iPascending order us listl=[9,16,6,26,0] print("unsorted list] is", list!) 1g bubble sort: for jin range(len(listl 1) for iin range(len(listl)-1): if list [iptist [#1] Fist fil fist [+1 tise [i+ 1 list fi] print(istl) else: print(istl) print() print("sorted list is"ist1) Output: unsorted listl is [9, 16, 6, 26, 0] [9, 16, 6, 26, 0] (9, 6, 16, 26, 0] (9, 6, 16, 26, 0] 19, 6, 16, 0, 26] [6, 9, 16, 0, 26] {6,9, 16, 0, 26] [6,9,0, 16, 26] 16,9, 0, 16, 26] [6, 9,0, 16, 26] [6, 0,9. 16, 26] [6, 0, 9, 16, 26] [6,0, 9, 16, 26] [0, 6,9, 16, 26] [0, 6,9, 16, 26] [0, 6, 9, 16, 26] [0, 6,9, 16, 26] sorted list is (0, 6, 9, 16, 26] HIf we want to reduce no of iterations/steps in output: C/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/[Link] 69 list1=[9,16,6,26,0] print("unsorted list is", list) for j in range(len(listl)-1,0,-1): for iin range() if its [i}>listl [+1] list [[Link] i+ 1]-Uist [+1] ist] print(istl) else: print(list) print() print( "sorted list is"fist1) Output: (C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/[Link] unsorted listl is [9, 16, 6, 26, 0] {9, 16. 6,26, 0] 19, 6, 16, 26, 0] [9, 6, 16, 26, 0] [9.6, 16, 0, 26] [6,9, 16, 0, 26] [6.9. 16, 0, 26] [6. 9,0, 16, 26] [0, 6, 9, 16, 26) sorted list is 0, 6, 9, 16, 26] # Ina different way: listl=[9,16,6,26,0] print("unsorted listl is", list!) for jin range(len(list1)-1): for iin range(len(list1)-1-): if ist. [i}>listl [i+]: list i listl (i+1 list! [i+ 1] list [i] print(listl) else print(listl) print() print("sorted list is" list!) Output: ‘CUsers/ MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/[Link] 70 unsorted listl is (9, 16, 6, 26, 0] [9, 16, 6, 26, 0] (9,6, 16, 26, 0] (9,6, 16, 26, 0] (9,6, 16, 0, 26] {6,9, 16,0, 26] [6, 9, 16, 0, 26) (6.9, 0, 16, 26) [6, 9, 0, 16, 26) [6, 0, 9, 16, 26) [0, 6, 9, 16, 26) sorted list is [0, 6, 9, 16, 26] # Program to give input from the user to sort the elements lis ‘num=int(input(“enter how many numbers:")) print("enter values") fork in range(num): list1 append(int(input0)) print(“unsorted list! is", list!) for in range(len(listl)1): for iin range(leni{istl)-1): if list i> list [i+ 1]: list [ili fi+1 list [i+ Tit [i] print(listl) else: print(listl) print() rint("sorted list is", Output: (CUsers/ MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/bubb4. py enter how many numbers:5 enter values 5 7 4 66 30 unsorted listl is (5. 77, 4, 66, 30] (5,77, 4, 66, 30] n |, 66, 30, 77] 4,5, 66, 30, 77] (4,5, 66, 30, 77] [4, 5, 30, 66, 77] (4,5, 30, 66, 77] (4, 5, 30, 66, 77] (4,5, 30, 66, 77] [4, 5, 30, 66, 77] 4,5, 30, 66, 77] (4,5, 30, 66, 77] [4, 5, 30, 66, 77] [4, 5, 30, 66, 77] [4,5 30, 66, 77] sorted list is [4, 5, 30, 66, 77] bubble sort program for descending order for jin range(lenilist!)-1): fori in range(len(list! 1) list [ili [#+1} list [i] list (i+1}-list! [i+1 ] fist [i] print(istl) else: print(list) print() print("sorted list is" list1) Output: CiUsersMRCET/AppDataocal/ProgramsPython/Python38-2pyyy/bubbdesepy unsorted list] is [9, 16, 6, 26, 0] (16, 9, 6, 26, 0] [16, 9, 6, 26, 0] 16, 9, 26, 6, 0] [16, 9, 26, 6, 0] [16, 9, 26, 6, 0} [16, 26, 9, 6, 0] [16,26, 9, 6,0] [16,26, 9, 6,0] (26, 16, 9.6, 0] n [26, 16, 9, 6, 0) [26, 16, 9, 6, 0} (26, 16,9, 6,0] (26, 16,9, 6, 0} [26, 16, 9, 6, 0) [26, 16, 9, 6, 0) (26,16, 9, 6,0] sorted list is [26, 16, 9, 6, 0] Selection Sort: Sort (): Built-in list method Sorted (): built in function © Generally this algorithm is called as in-place comparison based algorithm, We compare numbers and place them in correct position. ‘Search the list and find out the min value, this we can do it by min () method. ‘© We can take min value as the first element of the list and compare with the next element until we find small value. Algorithm: 1. Starting from the first element search for smallestibiggest element in the list of numbers. 2. Swap min/max number with first element 3. Take the sub-list (ignore sorted part) and repeat step 1 and 2 until all the elements are sorted #Write a python program to arrange the elements in ascending order using selection so listl=[5,3,7,1,9.6] print(listl) for iin range(len( list!) ‘min_val=min(list[i:)) min_ind~list] index(min_val) listI[i]Jist][min_ind]=listl[min_ind] list] print(list!) Output: (C/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/selectasce py 5,3,7, 1,9, 6] #Write a python program to arrange the elements in descending order using selection sort: listI=[5,3,7,1,9,6] print(listl) fori in range(len( list!) ‘min_val-max(list[i:]) ‘min_ind=listindex(min_val) B listl i) list [min_ind]-listl [min_ind list [i] print(list!) Output: C:/Users/MRCET/AppData/LocalPrograms/Python/Python38-32/pyyy/[Link] (5.3.7. 1,9,6] 19.7.6,5,3, 1] Note: If we want the elements to be sorted in descending order use max () method in place of min (). Insertion Sort: ‘© Insertion sort is not a fast sorting algorithm. It is useful only for small datasets, ‘© It isa simple sorting algorithm that builds the final sorted list one item at a time. Algorithm: 1. Consider the first element to be sorted & the rest to be unsorted. ‘Take the first element in unsorted order (u!) and compare it with sorted part elements(s!) Iful0: ‘my_list{pos]=my_list{pos-1] pos=pos-I my_list[pos|-current_element 51,0102]. num=int(input(“enter how many elements to be in list”)) insertionsort(listl) listI=[int(inputO) for i in range (num)] print(list1) Output: C/Users/MRCET/[Link]/Programs/Python/Python38-32/pyyylinserti py (0, 1,2, 3, 5, 10} # Write a python program to arrange the elements in descending order using insertion sort (with functions) def insertionsort(my_list we need to sorrt the unsorted part at a time for index in range(I len(my_list): current_element=my_listfindex] pos=index while current_element>my_list{pos-I Jand pos>0: ‘my_list{pos]-my_list{pos-1] pos=pos-1 my_list[pos|-current_element HlistI=[3,5,1,0,10,2] ” #insertionsort(listl) print(list1) ‘num=int(input("enter how many elements to be in list")) listI=[int(input()for i in range(num)] insertionsort(listl) print(list!) Output: (C/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyylinsertdese py center how many elements to be in list 5 8 1 10 2 (10, 8, 4,2, 1) ‘Merge Sort: Generally this merge sort works on the basis of divide and conquer algorithm. The three steps need to be followed is divide, conquer and combine. We will be dividing the unsorted list into sub list until the single clement in a list is found. Algorithm: 1. Split the unsorted list. 2. Compare each of the elements and group them 3. Repeat step 2 until whole list is merged and sorted. # Write a python program to arrange the elements in ascending order using Merge sort (with functions) def mergesort(listl) if len(listl)>1 smid=len(listl V2 left_list-list[:mid] right_list-list[mid:] mergesort(left_list) mergesort(right_list) i-0 jro ko while i=pivot: tight=tight-1 if right=pivot: lefi-left+1 while left<=right and list [right]}<=pivot: tight=right-1 ifrightsleft: break else: list] [left] ist [right]-list] [right] list [lef] list [first list] [right}=list [right] ist! [first] retum right def quicksort(listlfirstast): if first Enqueue is an operation which adds an element to the queue. AS stated earlier, any new item enters at the tail of the queue, so Engueue adds an item to the tail of a queue, Enquove Dequeue — It is similar to the pop operation of stack i., it retums and deletes the front element from the queue. Doaveve isEmpty — It is used to check whether the queue has any element or not. isFull + It is used to check whether the queue is full or not. Front — Itis similar to the top operation of a stack ic., itretums the front element of the queue (but don’t delete it). Before moving forward to code up these operations, let’s discuss the applications of a queue. 94 Applications of Queue Queues are used in a lot of applications, few of them are + Queue is used to implement many algorithms like Breadth First Search (BFS), ete. + Ttean be also used by an operating system when it has to schedule jobs with equal priority + Customers calling a call center are kept in queues when they wait for someone to pick up the calls Queue Using an Array We will maintain two pointers - ‘ail and head to represent a queue. head will always point to the oldest element which was added and ‘ail will point where the new element is going to be added head tail ‘Queue To insert any element, we add that element at fail and increase the fail by one to point to the next element of the array. Suppose sail is at the last element of the queue and there are empty blocks before head as shown in the picture given below. In this case, our sail will point to the first element of the array and will follow a circular order. 95 tall head Initially, the queue will be empty ie, both head and tail will point to the same location ic, at index 1. We can easily check if queue is empty or not by checking if head and tail are pointing to the same location or not at any time tal head An Empty Queue IS_EMPTY(Q) If [Link] == [Link] return True return False Similarly, we will say that if the head of queue is 1 more than the fail, the queue is full tall head Queue Overflow IS_FULL@Q) if Quhead = [Link]+1 return True Return False Now, we have to deal with the enqueue and the dequeue operations, To enqueue any item to the queue, we will first check if the queue is full or not ie., Enqueue(Q, x) if isFullQ) Error “Queue Overflow” else Ifthe queue is not full, we will add the element to the fail Le, Q[Qtail] = x. head ta ENGUELE(2) Se While adding the element, it might be possible that we have added the element at the last of the array and in this ease, the fail will go to the first element of the array. : | : BEEBE Otherwise, we will just increase the fail by 1 Enquene(Q, x) Full(Q) Error “Queue Overflow” else Qa 7 Qu Qutail+1 dequeue, we will first check if the queue is empty or not. Ifthe queue is empty, then we will throw an Dequeue(Q, x) ifisEmpty(Q) Error “Queue Underflow” else To dequeue, we will first store the item which we are going to delete from the queue in a variable because we will be returning it at last. Dequeue(Q, x) if isEmpty(Q) Error “Queue Underflow” else x= QIQuhead] ‘Now, we just have to increase the head pointer by 1. And in the case when the head is at the last element of the array, it will go 1 | cea, tm Lt Dequeue(Q, x) ifisEmpty(Q, Error “Queue Underflow” else X= Q[Qhead] if [Link] == [Link] Quhead=1 98 else Quhead = [Link]+1 class Queue: def _init_(self, size) selffhead = [Link] self.Q = [0}*(size) selfisize = size def is_empty(self): iff selftail = self head: retum True retum False dof is_full(self) ifselfhead = selftail+1 retum True retum False def enqueue(self, x): if-selfis_full0: print("Queue Overflow") else: 99 [Link]] = x if [Link] = self'size: selfitail = 1 else: [Link] = selftail+1 def dequeue(self): if selfis_empty(: print("Underflow") else x= selfQ[selfhead] if self head == selfsize: selfthead = 1 else: self head = self head+1 retum x def display(self): i=selfhead while(i < selftail): print(sel£QUil) self'size): 100

You might also like