0% found this document useful (0 votes)
36 views

Data Structure - Searching and Sorting

Uploaded by

n611704
Copyright
© © All Rights Reserved
Available Formats
Download as PDF or read online on Scribd
0% found this document useful (0 votes)
36 views

Data Structure - Searching and Sorting

Uploaded by

n611704
Copyright
© © All Rights Reserved
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 16
Unit i: Computational Thinking and Programming -2 Visit to website: learnpythondcbse.com COTY a-ak Ser Le eae a a Structure - Searching & Sorting 1 What is data structure? 2 | Data type vs data structure 3 Different data structures 4 Linear list 5 Linear search 6 Binary search 7 Bubble sort 8 Insertion sort Page tof 16 rapythonacbse com ‘Computation: Chapter 9- Data Structure - 1 > In computer science data structures is a way of organizing and storing the data in a computer so that it can be accessed and modified efficiently. > The main idea is to reduce the space and time complexities of different tasks. > A data structure has well-defined operations, behaviour and properties. > All data structures are data types, but not all data types are data structures. > Data type is used so that compiler can understand the type of data that will be stored in a variable and accordingly allocate memory block for variable for example: int, float and string etc. > Data Structures are efficient ways to store data, so that we can access and manipulate data accordingly for example: list, stack and queue etc. Page 2 of 16 puttin era Chapter 9- Data Structure - 1 DATA STUCTURE een: ee ener Pr Rng > A list is a data structure in Python that is a mutable, or changeable, ordered sequence of elements. > Lists are used to store data of different data types in a sequential manner. > Index of first item is 0 and the last item is n-1.Here n is number of elements in a list. | 10/5/65] isl Page 3 of 16 Unit i: Computational Thinking and Programming -2 Visit to website: learnpythondcbse.com Chapter 9- Data Structure - 1 > Array can be Single Dimensional or Multidimensional. In Python arrays are implemented through List data types as Linear List or through NumPy arrays. Its syntax is: Variable name [index] (variable name is name of the list). For Example: To create an empty list, use a statement like la=[] @ To create a list that contains a sequence of values, separate the values by commas inside square brackets ([ ]) L2=[1, 2,3] To create a list that contains 3 string elements. L3 = [“Delhi”, “Chennai”, “Mumbai”] To create a list that contains different types of elements L4 = [“abe”, 10, 20] Adding the elements in the list can be achieved using the append(), extend() and insert() functions. > The append() function adds all the elements passed to it as a single element. Page 4 of 16 Unit i: Computational Thinking and Programming -2 Visit to website: learnpythondcbse.com Chapter 9- Data Structure - 1 > The extend() function adds the elements one-by-one into the list. > The insert() function adds the element passed to the index value and increase the size of the list too. my_list = [1, 2, 3] Pareles et) eee #add a list [555, 12] asa single element my_list.append([555, 12]) print(my_List) ssssessseeessessseesseeeeseeeesseeeseees #add a list ([234, 'more_example' ] )as different elements my_list.extend([234, ‘more_example']) print(my List) secssessecceessessseeeessesssceeeeensesees #add element ‘insert_example’ at specified position 1 my_list.insert(1, ‘insert_example') ger (ry LCs >) enone Output: [1, 2, 3] a [1, 2,3, [555, 12]] qeeccseeeeceeeeeeeeeeeseeeeeeeeeeeeeeesneeenees [1, 2, 3, [555, 12], 234, ‘more_example’] q.esccceseeeeeeeeeeeenee [1, ‘insert_example’, 2, 3, [555, 12], 234, ‘more_example’] ¢.....00: Page Sof 16 puttin Chapter 9- Data Structure - 1 > To delete elements, use the de/ keyword which is built-in into Python but this does not return anything back to us. > If you want the element back, you use the pop() function which takes the index value. > To remove an element by its value, you use the remove() function. my_lst = [10, 20, 30, ‘example’, 31.132, 1, 3] # delete element at index 5 del my_1st[5] print(my_Ist) «++ # remove element with value my_1st.remove(' example") print(my_Ist) s+ # pop element from list x = my_lst.pop(1) print('Popped Element: ', x, ' List remaining: # empty the list my_1st.clear() print(my_Ist) +++ Output: [10, 20, 30, ‘example’, 31.132, 3] 4 [10, 20, 30, 31.132, 3] «-- Popped Element: 2 List remaining: 10, 30, 31.132, 3] « Page 6 of 16 ‘Computation: ing Chapter 9- Data Structure - 1 Accessing elements is the same as accessing Strings in Python. You pass ‘ogrammi the index values and hence can obtain the values as needed. Example: my_Ist = [10, 20, 30, ‘example’, 31.132, 1, 3] #access elements one by one for element in my_Ist: print (element)+ #taccess all elements print (my_1st) #access index 3 element print(my_lst[3]) “* #access elements from @ to 1 and exclude 2 print (my_1st[@:2]) «++ #access elements in reverse print(my_lst[::-1])"*" Output: example 31.132 1 3 [10, 20, 30, ‘example’, 31.132, 1,3] «.. example ¢- [10,20] < [3, 1, 31.132, 'example', 30, 20, 10] «+ Page 7 of 16 [[ Uniti: Computational Thinking and Programming-2—~—~—~=~*S*S*S*«nRto wes leaempythondcbee com J ‘Computation: _—————— 9- Data Structure Linear ee arene errr ra each element of linear list is compared with the given item to be searched one by one. This method traverse the linear list sequentially to located the given item. For Linear Searching item need not be in any order, it can be performed on random list. Linear Searching is suitable for small list only. Best Case: when item to be search is at first position Worst Case: when item to be search is at last position or not present Average Case: when item is somewhere in list other than first or last position. a Let's first develop an algorithm for performing a linear search. We will then convert this into a Python script. > Let's start with a list of numbers, say 10 of them > First, we will ask for a number we think may be in the list. We will call this variable "srchltem" > Also, we will set a flag variable called "flag" to false > Now loop thru the entire list from start to end - Compare the item at the current position in the list with "srchltem" Page 8 of 16 Unit i: Computational Thinking and Programming -2 learnpythondcbse.com Chapter 9- Data Structure - 1 - If it matches then set "flag" to true and exit the loop, else move on to the next position > Otherwise, if we have searched the entire list, "srchitem" was not found, so "flag" remains false B Uist LinearSearchpy - D/Amjad CSUs nea Searehpy 365) ee or Fie eae vat Run Options Window Help # Created by: learnpython4cbse.com 5 # Linear Search Ast = [40, 20, 70, 50, 120, 540, 210, 640, 120, 320] print ("List has the items: ', 1st) srchItem = int(input("Enter a number to search for: ')) flag = False for i in range(len(1st) if st{i] == srchTtem: flag = True print (srchItem, ' was found in the list at index ', i) break if flag == False: print (srchItem, ' was not found in the lis [a Pytton 365 Stet File Est Shell Debug Options Window Help RESTART: D:/Amjad_CS/List_LinearSearch.py = List has the items: [40, 20, 70, 50, 120, 540, 210, 640, 120, 320] Enter a number to search for: 30 30 was not found in the list D>> >>> RESTART: /pmjad_CS/List_LinearSearch.py List has the items: [40, 20, 70, 50, 120, 540, 210, 640, 120, 320] Enter a number to search for: 70 70 was found in the list at index 2 >>> Unet5 Cote ge 9 of 16 puttin Chapter 9- Data Structure - 1 = The binary search algorithm can be used with only a sorted list of elements. Binary search follows a divide and conquer methodology. It is faster than linear search but requires that the array be sorted before the algorithm is executed. Assuming that we're searching for a value val in a sorted array, the algorithm compares val to the value of the middle element of the array, which we'll call mid. -- The search process initiates by locating the middle element of the sorted array of data. -- After that, the key val is compared with the element. -- If the key val is smaller than the middle element, then searches analyses the upper values to the middle element for comparison and matching. -- In case the key val is greater than the middle element then searches analyses the lower values to the middle element for comparison and matching. Page 10 0f 16, gramming -2 Visit to webs rpythondcbse.com Chapter 9- Data Structure - 1 EXAMPLE : Binary Search putational © List of 10 elements [3,6,9,12,15,18,21,24,27,30] © Left=L First Iteration Right=R Lojaj2i3ajajsj6|7|ajo)} mom E CEC IESE CPS aPZ array VUE Lst{mid] = (L +R )/2 MID G id] = (| e Second Iteration (5 6|7\8 9] The lower half of the list The iteration continue and is dropped because 27 is data on decreasing in greater than 15 same until 27 is found A. You have a List of sorted values ranging from 3 to 30 and need to locate 18. B. The average of the lower and upper limits is (L + R) / 2 = 4. The value being searched is greater than the mid which is 4. C. The List values less than the mid are dropped from search and values greater than the mid-value 4 are searched. D. This is a recurrent dividing process until the actual item to be searched is found. Page 11 0f 16, Unit i: Computational Thinking and Programming -2 Visit to website: learnpythondcbse.com Chapter 9- Data Structure - 1 [a UstinaySearchpy- DiAijed.CSfistinagBearchey (365 SN 6 ue File Edt Format Run Options Window Help # Created By: learnpython4cbse.com 5 # Binary Search Lst = [5,7,10,12,15,18,20, 34, 40, 56, 60,80, 90,100] start = 0 end = len(Lst) - 1 mid = (start + end) // 2 # We took found as False that is, initially # we are considering that the given number # is not present in the list unless proven num=int (input ("Enter number to be searched: ")) found = False position = -1 Si while start <= end: if Lst{mid) == num: found = True position = mid print ("Number $d found at position $d'%(num, position+1) break if num > Lst (mid): start = mid +1 mid = (start + end) // 2 mid - 1 (start + end) // 2 print ('Number td not found" tnum) 7 Led Cob RESTART: D:/Amjad_Cs /ListBinarySearch.py Enter number to be searched: 20 Number 20 found at position 7 >>> RESTART: D:/Amjad_Cs /ListBinarySearch.py Enter number to be searched: 25 Number 25 not found Page 12 0f 16, puttin Chapter 9- Data Structure - 1 Sorting Sorting is the process of arranging a list of elements in a particular order (Ascending or Descending). > The bubble sort makes multiple passes through a list. > It compares adjacent items and exchanges those that are out of order. > Each pass through the list places the next largest value in its proper place. > Inessence, each item “bubbles” up to the location where it belongs. Complexity : The complexity of bubble sort is O(n?) in both worst and average cases, because the entire array needs to be iterated for every element. EXAMPLE : Bubble Sort First Pass Page 13 of 16, Gai Computational Tiling and Progamming 2 Vi fo webs lenannthonabee com Chapter 9- Data Structure - 1 bbleSorepy (3.65) File fat Format Run Options Window Help # Created By: learnpython4cbse.com # Bubble sort jist = 0 num = int (input ("Enter No of Element : ")) for i in range (num): val = int(input("Enter the %d Element of List : " $i)) lst append (val) for i in range(num -1): for j in range(num - i - 1): if(st{j] > Ist{j + 11): tmp = lst(j] Ast{j] = 1lst{j + 1) Ist{j + 1] = tmp ul print("The Sorted List in Ascending Order : ", lst) File Edit Shell Debug Options Window Help Enter No of Element : 5 e Enter the 0 Element of List : 2 Enter the 1 Element of List : 1 Enter the 2 Element of List : 89 Enter the 3 Element of List : 43 Enter the 4 Element of List : 78 Y The Sorted List in Ascending order : [1, 2, 43, 78, 89] . Ln13 Coks Page 14 0f 16 ‘Visit to website: learnpythondcbse.com Chapter 9- Data Structure - 1 In insertion sort algorithm, every iteration moves an element from unsorted portion to sorted portion until all the elements are sorted in the list. Insertion sort is a simple sorting algorithm that works the way we sort playing cards in our hands. Step by Step Process The insertion sort algorithm is performed using the following steps... EXAMPLE : Insertion Sort Step 1 - If it is the first element, it is already sorted return 1; Step 2 - Pick next element Step 3 - Compare with all elements in the sorted sub-list Step 4 - Shift all the elements in the sorted sub-list that is greater than the value to be sorted Step 5 - Insert the value Step 6 - Repeat until list is sorted. (67/8 /10/11/12/16 18 Page 15 of 16, Unit i: Computational Thinking and Programming -2 Chapter 9- Data Structure - 1 ‘Visit to website: learnpythondcbse.com le Edit For Run Options Window Help # Created By: learnpython4cbse.com # Insertion Sort ist = (] size = int(input("\nEnter size of the list: ")) for i in range(size): ele = int(input ("Enter the element: ")) 1st. append (ele) for i in range(1, len(lst)): ist [il jrai-1 while j >= 0 and ky < lst{j]: ist{j + 1] = 1st{j] 3-1 Ist{j + 1] = print ('\nThe sorted list: ', 1st) print (*\n") LB Python 365 Shell File Edit Shell Debug Options Window Help RESTART: D:/Amjad_CS/List_Ins * ertionSort.py Enter size of the list: 8 Enter the element: 10 Enter the element: 8 . Enter the element: 7 . Enter the element: 16 Enter the element: 18 Enter the element: 6 Enter the element: 11 Enter the element: 12 The sorted list: [6, 7, 8, 10, 11, 12, 16, 18] Lei Coto Page 16 of 16,

You might also like