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
You are on page 1/ 19
poo
Unit |
Searching and Sorting
1. The sorting is uset
desired order.
tweful for arranging the data in desired order. Aftep
red element can be located easily.
ful in database applications for arranging the data iq
2. In the dictionary like applications the data is aranged in sorted order,
3. For searching the element
required.
Q2 What is searching 7
“Ans. : When we want to find out particular record
from the list of elements, the sorting is
the uniqueness of the element the sorting is required.
st pair from the list of elements the soning is
3.2 : Searching Techniques
ly ftom the
elements then there are various mt arching that
methods are called searching methods. Various
these searching methods are known a searching
« Example
ty of this algorithm jg :
ly With the ve ofa 00 TH fie conpety
ue of m Sequential seach is not Satisfactory solution,aes
oy 31 594 09 = (sv
Amt; (aly
Sn a
won
‘ons ne ap 1S
oF flv
xD; ta spagg wat
09> OF PE OF =leV oN
= 8 Ort 40 ns ST
Ky 1 meas ma mTFundamental of Date Stuctars
‘Advantages and disadvantages of binary soarch
Advantage
Isr. No)
1
ient technique.
plex to implement.
Linear search method
is the difference between linear search and binary
1
‘method in which the element is
“The linear search is. a searching|The
searched by scanning the entite| div
|lise from first clement to the| mi
as.
Many times entire list is
searched.
|i simple to implement.
1t involves computation for finding
the middle element.
It is an efficient searching method.
ribonacel search rather than
tee 9 Be sabes fom fed 8 enc, weenie
ems sai. As we nome the
understand how Fibonacci search
7 enple, suppose, folowing i the tof cant? Mil comer oxe
ar()
(:[+1+ [ols cee
1 ‘ss 7- Of elements = 7
‘We will always compute 3 variables ie, a,b and f
With these initial values we will
lis. Each time we will compare key
If (Key < ar [f)
f=f-a
a=b-agor
Irie Tengh of sven amy be 8 et} sd te ae
searched be key 4
‘Then we use the following steps to find the ne
steps
ile. 20 < arr [4]
i.e. if 20 < 40) > YesAccording :
* srabng Fibonacci 5
0
Hence retum value of i as the positon of key
‘ote that due to fbonacei numbering the search portion is “,
we need to compare very less number of elements,
on
if (key < Elements{0)):
print(‘Element is not present”)
exit(0)else:
for {in range(1, ind + 1);
Mikey < Elements :
Start = Index{i- 1]
end = Index{i]
break
of Data Sructres gay Nadie bitinas
———_Searhing ad Sry \
ious method tht make we of ira sing we
2. Inetion Sort 3, Selection Sort 4, Quick
for iin range(start, end + 1);
if (key == arti] );
flag=1
break
ifflag ==1:
Print("Element is Found at index’, i)
else : descending,
= ascending order.
Print(‘Element is not present") - a ee ‘in which the elements:
from low value to high value In other words elements ae
der.
Print("\n Program For Index Sequential Search")
array = [11,15,22,24,26,32,94,38]
n = len(array)
Output
Program For Index Sequential Search
Element is Found at index 5
3.3 + Types of Sorting
al sorting techniques.
Giajezpisia interna! and exterafl oF [SPU : June-22, Marks 8]2 0
2 0 8
1 9 4
1,2 be the given list of elements, We
oc say Ali] and Afj). If Afi] > AG) then ma oe
¢
Pass |
es 4 1 een
ORE ia yh we NY
i '
5 10 4 18 7 1 2 —
Ae | Gh
5 4 10 18 7 1 2 AND f
we) : ei
ae ta ee
Ks}
10 7 18 1 2 4 | z z 2
Wy VW
SOP e TRA. eG 2 1 4a 7 ale
oS SA
$A 204 See
eS
Pass It ‘ : ; : ae
Ak oe
Coe ee = — , oe
/ :
ie KK SKA
oe) Yee
5 10 7
elements.
‘ This is the sorted list of
ee 0 _ [212 Write a Python program for sorting the elements using Bubble
vert
‘def Bubble(arr,n): 2
F t=0
2 8
BR 12 0 8 E
a Sr
, iaFundamentals of Date Sructures, 3.18
——aoen it _ eel
{for {in range(n-1)
corse 210 do
{gmp + Alil/mare Allth element
je f//st at previous eloment of Aj}
‘aniloG> =OANDIAU}>tomp)do
ring all the previous elements of Ali with
{f any greeter element is found then insert.
ition
] [ofa eofo]ez]oe] ts] compare 50 and
ea
: Sorted array Al0.,.n-1] in ascending orderFundamentals of Data Structures
Cols] ep
eee
bated Unsorts
zone
(eLre] ELRTTS] con so
1 eters in sorted
x Lead the elements A(o
tine zone
um element) fi ene. Ase i
°
oO \ 1a 5
(OCOD a EE Ee
Sorted Unsorted | See
ae zone win Sei
‘loner
smallest element is found, swap it with Af)
[rolso[so[sofrs] — [eaToe]is] o 1) 2h
[+L + [TTT]
=
Unsonaa
eafrofsofeo|solra] Bala]
sme
2
(gs 0 1 2 Seem
ees
Sorted Unsored
zane Tone
Pepper) fl pass 3:
aay)
Sorted Unsorted
pel zone
[voJosTso]15]s0]40]s0[7,)
Sorted
HistFundamentals of Data Sructares 3-3 Searching ag
Oo ren 7 5
pivot
jy and AGI
iReNc es won
ee eas fy
oe “ y a
ui 4 2 3 4 5 j i
GE TeTaTeTer] oi Swap AILow] and Af}
Pass 5: wre
Oia rene 4 te PME
Delete Teta] SF ;
t Pivot i i
po. 4 7
i
cet 3
EE
n 8 [8 37 8 2 6
This sa sorted
3
‘Asj> i, we will swap AG] and AfLow]
After pass 2:
As }> i swap 92 with $7.
eet‘After pass 4:
na
aa Program For Quick Sor’) : :
et"
5 21 Bie sso aren 2 ore Z ——
; ‘Aeyr)
Afar pass 5 : = ay oe
eer,
—— resin range) ’
ne enn)
Sef Quick{arrJow high): a
Mow>>
will then be decrement
will be made, Finally,anti] = temp
d=ay2
Print(\n Program For Shell Sort’)
Print("\nHow many elements are there in Array?")
n= int(input())
array = []
iso
for i in range(n);
Print("\n Enter element in Array’)
item = int(input())
array.append{item)
print('Original array is\n")
print(arrey)
ShellSort(array.n)
print("\n Sorted Array is")
print(array)
Output
Program For Shell Sort
How many elements are there in Array?
5
Enter element in Array
10
Enter element in Array
40
Enter element in Array
50
3 following data in ascending order using Radix Sort
06, 45, 60, 140, 50. EF [SPPU : June,Step 2:
Sort the elements according to second last digit and sort them,
Second last digit | Element
aor onl umber of meni tary
+ ore the unsorted ME inh gray
+ now te simple Poel i on he
4, Sort the elements according tothe Jag,
0 00.
0 06
lent by gt by dig,
8 tes second lt ig et
5. Thus the clemens soul! Be ed a
6: store the sorted element inthe ary and prt ue
7. Stop.
1
2
3
4
5 30
6
7
@
Stop 3:
Sort the elements according to 100 position of the element and
them.
——_—
100" position Element
06,25, 45,50, 60
def countingSort(arr,place): a
140 os
n= len(art)Fundamentals of Date Structures 3-29
while i >=-0:
index = ari] H place
result{count{index % 10] - 1] = ari]
Count[index % 10] -= 1
sit
#placing back the sorted elements in original
for in range(0, n):
array = result}
print(\n Program For Radix Sor’)
‘Print(\nHow many elements are there in Array?*)
1 = int{input())
ary = []
i=0
for in rango(n):
print('\n Enter element in Array’)
‘item = int(input()
array append(item)
pprint(‘Original array is\n')
rint(array)
RadixSort(array)
print('\n Sorted Array is")
rint(azray)
Output
Program For Radix Sort
‘How many elements are there in Array?
6
3?
Gas Wit am algorithm for radi or,
‘hoe he al miner of ene ia ea,
2, Store the unsorted elements inthe ama
3, Now the simple procedure is to sor the elements by digit
4, Sort the elements according tothe last digit then
000.Fundamentals of Data Sructures 3-31
Sethe Soy
Sonssponding location of element ie element 1 appeared twice, Alone
2 is not present, element 3 appeared twice tnd element 4 appeared ong
TH
Count [ 2 [0
2|4
SP 2: Now we will rete anther ary B in which we wil ores
of counts for given index.
atalt2
aE
= oh]
= [afenaes)
Simply copy first index value of count array 16 B.
For filling up rest of the elements to B array copy the sum of previous
index value of B with current index value of count array.
YW
* (es
‘consider array A and B for creating two more amas
‘and Element.
| — emai
“ CEE A postion 5
positon CEeETT St: Raa sen
aa
hence copy 4Searching eng
Step 5 : Next elements 3. The poston of tis 4in ray B,
‘CERT
5 co
rooton [1 T2 Ta Toys]
Step 6 : Next element is 1. The postion of it in aay B is 1,
CREE
1
*GPPT
roston [7] 2] 8]
Bement [3 Ts] 13
Step 7 : Next element is 3. In array B its position is 3.
GPP)
8 [o[2[s [es
Position [ 1
fat rh iy aaa
coyFundamentals of Data Siractures 3-38 Sst dng
print(‘Originel array is\n")
‘print(erray)
countingSortazrey)
Pinta Sorted Amey i) ea:
print(array) print ESS
the elements tng bucket an,
Output on 2 ee 1D 36 70 goa
Program For Counting Sort y
st
ow many slmiente ae ther in ray? gs: We il SUP 22 AT 8 fg
7
Enter elamentin Amey
5
Enter element in Array
3
Enter element in Aray
5
Q.22 What is Bucket sort algorithm ? é
tanec ake Sm is a sorting technique in which ary i paring ia Fe
buckets. Each bucket is then sorted individually, using some other sing
thm such as insertion sort, 3Fundamentals of Data Structures 3-37
Q.24 Compare the best case, worst case and average
complexitites of various sorting algorithms.
Ans. :
SSE ting
Sorting
Average case
technique
Set [So IO
[secre elo): o[aey Sige
Radix sort Ofnlogn) O(nlogn) O(nlogn)
Quick sort O(nlogn) O(nlogn) O(a?)
Heap sort O(nlogn) O(nlogn) O(nlogn)
Shell sort Ofalogn)
On)