SlideShare a Scribd company logo
1 of 43
Sorting & Searching
Searching
Internal Search
The search in which the whole list resides in
the main memory is called internal search.
External Search
The search in which the whole list resides in
the Secondary memory is called external
search.
Types of searching Algorithm
• Linear or Sequential searching
• Binary searching
Algorithm For Linear Search
LINEAR(DATA ,N,ITEM,LOC)
1.Set K:=1 and LOC := 0.
2.Repeat Steps 3 and 4 while LOC = 0 and K<=N.
3.If ITEM = DATA[K] ,then Set LOC:= K.
4.Set K:=K+1.
5.If LOC = 0,then:
Write: ITEM is not in the array DATA.
Else:
Write: LOC is the location of ITEM.
6.Exit.
Advantages
• Not Expensive.
• List/Array may or may not be sorted.
Disadvantages
• Less Efficient.
• Time consuming.
Algorithm For Binary Search
BINARY(DATA , LB , UB, ITEM , LOC)
1. Set BEG:= LB, END:=UB and
MID = INT((BEG+END)/2).
2. Repeat Steps 3 and 4 while BEG<=END
and DATA[MID]!=ITEM.
3. If ITEM< DATA[MID] ,then:
Set END := MID-1.
Else:
Set BEG := MID+1.
4. Set MID := INT((BEG+END)/2).
Algo. Cont.
5. If DATA[MID]=ITEM, then:
Set LOC:= MID.
Else:
Set LOC:= NULL.
6. Exit.
Advantages
• Extremely Efficient
• Less Time Consuming
Disadvantages
• Expensive
• List/Array may be sorted.
Introduction to Sorting
• Sorting: An operation that arranges items into groups
according to specified criterion.
A = { 3 1 6 2 1 3 4 5 9 0 }
A = { 0 1 1 2 3 3 4 5 6 9 }
Why Sort and Examples
Consider:
• Sorting Books in Library (Dewey system)
• Sorting Individuals by Height (Feet and
Inches)
• Sorting Movies in Blockbuster
(Alphabetical)
• Sorting Numbers (Sequential)
Types of Sorting Algorithms
There are many different types of sorting
algorithms, but the primary ones are:
• Bubble Sort
• Selection Sort
• Insertion Sort
• Merge Sort
• Quick Sort
• Radix Sort
• Heap Sort
Complexity
• Most of the primary sorting algorithms run
on different space and time complexity.
• Time Complexity is defined to be the time
the computer takes to run a program (or
algorithm in our case).
• Space complexity is defined to be the
amount of memory the computer needs to
run a program.
Complexity (cont.)
Complexity in general, measures the
algorithms efficiency in internal factors such
as the time needed to run an algorithm.
External Factors (not related to complexity):
•Size of the input of the algorithm
•Speed of the Computer
•Quality of the Compiler
O(n), Ω(n), & Θ(n)
• An algorithm or function T(n) is O(f(n))
whenever T(n)'s rate of growth is less than or
equal to f(n)'s rate.
• An algorithm or function T(n) is Ω(f(n))
whenever T(n)'s rate of growth is greater than
or equal to f(n)'s rate.
• An algorithm or function T(n) is Θ(f(n)) if
and only if the rate of growth of T(n) is equal
to f(n).
10
Common Big-Oh’s
Time complexity Example
O(1) constant Adding to the front of a linked list
O(log N) log Finding an entry in a sorted array
O(N) linear Finding an entry in an unsorted array
O(N log N) n-log-n Sorting n items by ‘divide-and-conquer’
O(N2
) quadratic Shortest path between two nodes in a graph
O(N3
) cubic Simultaneous linear equations
(Binary)
Finding 8:
9
50
22
21
8
5
1
(Linear)
Finding 8:
9
50
22
21
8
5
1Front
Initial:
Final:63
http://www.cs.sjsu.edu/faculty/lee/cs146/23FL3Complexity.ppt
Big-Oh to Primary Sorts
● Bubble Sort = n²
● Selection Sort = n²
● Insertion Sort = n²
● Merge Sort = n log(n)
●Quick Sort = n log(n)
Time Efficiency
• How do we improve the time efficiency of a
program?
• The 90/10 Rule
–90% of the execution time of a program is spent in
–executing 10% of the code
• So, how do we locate the critical 10%?
– software metrics tools
– global counters to locate bottlenecks (loop
executions, function calls)
Time Efficiency Improvements
• Possibilities (some better than others!)
• Move code out of loops that does not belong
there (just good programming!)
• Remove any unnecessary I/O operations (I/O
operations are expensive time-wise)
• Code so that the compiled code is more
efficient
•Moral - Choose the most appropriate
algorithm(s) BEFORE program implementation
Selection Sort
Selection Sort
MIN(A,K,N,LOC)
1. Set MIN = A[K] and LOC = K
2. Repeat for J=K+1, K+2 ……… N
If MIN>A[J], then Set MIN = A[J]
and LOC = J
End of Loop
3. Return
Selection Sort
SELECTION (A,N)
1. Repeat steps 2 and 3 for K=1, 2 ……… N-1
2. Call MIN(A,K,N,LOC)
3. Set TEMP = A[K]
A[K] = A[LOC]
A[LOC] = TEMP
End of Step 1 Loop
4. Exit
Complexity of the Selection Sort
• Worst Case
– O(n2)
• Average Case
– O(n2)
Insertion Sort
Insertion Sort
Insertion Sort
INSERTION (A,N)
1. Set A[0] = - ∞
2. Repeat Steps 3 to 5 for K = 2,3,….N
3. Set TEMP = A[K] and PTR = K-1
4. Repeat while TEMP<A[PTR]
1. Set A[PTR+1] = A[PTR]
2. Set PTR = PTR – 1
End of Loop
5. Set A[PTR+1] = TEMP
End of Step 2 Loop
6. Return
Complexity of the Insertion Sort
• Worst Case
– O(n2)
• Average Case
– O(n2)
BUBBLE SORT
Algorithm for BUBBLE SORT
BUBBLE(DATA , N)
1.Repeat Steps 2 and 3 for K=1 to N-1.
2.Set PTR := 1. // Initialize pass pointer PTR
3.Repeat while PTR<=N-K.
a) If DATA[PTR]>DATA[PTR+1],then
Interchange DATA[PTR] and
DATA[PTR+1]
b) Set PTR:= PTR+1
4. Exit.
Merge-Sort
Merge-Sort(cont.)
Merge-Sort (cont’d)
MERGE SORT
MERGE_SORT (A, BEG, END)
1. IF BEG<ENG
SET MID=(BEG+END)/2
CALL MERGE_SORT (A, BEG, MID)
CALL MERGE_SORT (A, MID+1, END)
MERGE(A, BEG, MID, END)
2. END
MERGE(A, BEG, MID, END)
1. SET I = BEG, J=MID+1, INDEX=0
2. REPEAT WHILE (I<=MID) AND (J<=END)
IF A[I]<A[J], THEN
SET TEMP [INDEX] = A[I]
SET I=I+1
ELSE
SET TEMP [INDEX]=A[J]
SET J=J+1
SET INDEX = INDEX +1
3. IF I>MID THEN
REPEAT WHILE J<=END
SET TEMP [INDEX]=A[J]
SET INDEX=INDEX+1
SET J=J+1
ELSE
REPEAT WHILE I<=MID
SET TEMP[INDEX]=A[I]
SET INDEX = INDEX +1
SET I=I+1
4. SET K=0
5. REPEAT WHILE K<INDEX
SET A[K]=TEMP[K]
SET K=K+1
6. END
QUICKSORT
Starting with first element of list do the operations
1. Compare from right to find element less than selected
and interchange
2. Compare from left to find element greater than selected
and interchange
44,33,11,55,77,90,40,60,33,22,88,66
22,33,11,55,77,90,40,60,99,44,88,66
22,33,11,44,77,90,40,60,99,55,88,66
22,33,11,40,77,90,44,60,99,55,88,66
22,33,11,40,44,90,77,60,99,55,88,66
22,33,11,40,44,90,77,60,99,55,88,66
Two Sublists are created:
Before 44 and After 44
37
Quick Sort Algorithm
QUICK (A, N, BEG, END, LOC)
1. [Initialize] Set LEFT= BEG, RIGHT=END and LOC=BEG
2. [Scan from right to left]
a) Repeat while A[LOC]<=A[RIGHT] and LOC != RIGHT
RIGHT=RIGHT-1
[End of loop]
b) If LOC=RIGHT then : Return
c) If A[LOC]>A[RIGHT] then
i) Interchange A[LOC] and A[RIGHT]
ii) Set LOC=RIGHT
iii) Go to step 3
[End of If structure]
3. [Scan from left to right]
a) Repeat while A[LEFT]<=A[LOC] and LEFT!=LOC
LEFT=LEFT+1
[End of loop]
b) If LOC=LEFT, then Return
c) If A[LEFT]>A[LOC], then
i) Interchange A[LEFT] and A[LOC]
ii) Set LOC=LEFT
iii) Goto step 2
[End of If structure]
38
(QuickSort) This algorithm sorts an array A with N elements.
1. TOP=NULL
2. If N>1 then TOP=TOP+1, LOWER[1]=1, UPPER[1]=N
3. Repeat Steps 4 to 7 while TOP!=NULL
4. Set BEG=LOWER[TOP], END=UPPER[TOP]
TOP=TOP-1
5. Call QUICK(A, N, BEG, END, LOC)
6. If BEG<LOC-1 then
TOP=TOP+1, LOWER[TOP]=BEG, UPPER[TOP]=LOC-1
[End of If structure]
7. If LOC+1<END then
TOP=TOP+1, LOWER[TOP]=LOC+1, UPPER[TOP]=END
[End of If Structure]
[End of Step 3 loop]
8. Exit
39
Radix Sort
Radix Sort
Radix Sort (or Bucket Sort)
• It is a non comparative integer sorting
algorithm
• It sorts data with integer keys by grouping
keys by the individual digits which share the
same significant position and value.
• A positional notation is required, but because
integers can represent strings of characters
(e.g., names or dates) and specially formatted
floating point numbers, Radix sort is not
limited to integers.
Radix Sort Algorithm
Let A be an array with N elements in the memory
• Find the largest element of the array
• Find the total no. of digits ‘NUM’ in the largest element
• Repeat Steps 4, 5 for PASS = 1 to NUM
• Initialize buckets (0 to 9 for numbers, A to Z for
Characters)
For i = 0 to (N-1)
Set DIGIT = Obtain digit number PASS of A [i]
Put A [i] in bucket number DIGIT
End of for loop
5. Collect all numbers from the bucket in order
6. Exit

More Related Content

What's hot

how to calclute time complexity of algortihm
how to calclute time complexity of algortihmhow to calclute time complexity of algortihm
how to calclute time complexity of algortihmSajid Marwat
 
02 order of growth
02 order of growth02 order of growth
02 order of growthHira Gul
 
Presentation on binary search, quick sort, merge sort and problems
Presentation on binary search, quick sort, merge sort  and problemsPresentation on binary search, quick sort, merge sort  and problems
Presentation on binary search, quick sort, merge sort and problemsSumita Das
 
asymptotic analysis and insertion sort analysis
asymptotic analysis and insertion sort analysisasymptotic analysis and insertion sort analysis
asymptotic analysis and insertion sort analysisAnindita Kundu
 
Intro to Sorting + Insertion Sort
Intro to Sorting + Insertion SortIntro to Sorting + Insertion Sort
Intro to Sorting + Insertion SortNicholas Case
 
Lecture 3 insertion sort and complexity analysis
Lecture 3   insertion sort and complexity analysisLecture 3   insertion sort and complexity analysis
Lecture 3 insertion sort and complexity analysisjayavignesh86
 
Quick sort Algorithm Discussion And Analysis
Quick sort Algorithm Discussion And AnalysisQuick sort Algorithm Discussion And Analysis
Quick sort Algorithm Discussion And AnalysisSNJ Chaudhary
 
Lecture 5 6_7 - divide and conquer and method of solving recurrences
Lecture 5 6_7 - divide and conquer and method of solving recurrencesLecture 5 6_7 - divide and conquer and method of solving recurrences
Lecture 5 6_7 - divide and conquer and method of solving recurrencesjayavignesh86
 
Lecture 4 asymptotic notations
Lecture 4   asymptotic notationsLecture 4   asymptotic notations
Lecture 4 asymptotic notationsjayavignesh86
 
Unit i basic concepts of algorithms
Unit i basic concepts of algorithmsUnit i basic concepts of algorithms
Unit i basic concepts of algorithmssangeetha s
 
Performance analysis(Time & Space Complexity)
Performance analysis(Time & Space Complexity)Performance analysis(Time & Space Complexity)
Performance analysis(Time & Space Complexity)swapnac12
 
Analysis of algorithn class 2
Analysis of algorithn class 2Analysis of algorithn class 2
Analysis of algorithn class 2Kumar
 
Design & Analysis of Algorithms Lecture Notes
Design & Analysis of Algorithms Lecture NotesDesign & Analysis of Algorithms Lecture Notes
Design & Analysis of Algorithms Lecture NotesFellowBuddy.com
 
Fundamentals of the Analysis of Algorithm Efficiency
Fundamentals of the Analysis of Algorithm EfficiencyFundamentals of the Analysis of Algorithm Efficiency
Fundamentals of the Analysis of Algorithm EfficiencySaranya Natarajan
 
3.8 quick sort
3.8 quick sort3.8 quick sort
3.8 quick sortKrish_ver2
 

What's hot (20)

how to calclute time complexity of algortihm
how to calclute time complexity of algortihmhow to calclute time complexity of algortihm
how to calclute time complexity of algortihm
 
02 order of growth
02 order of growth02 order of growth
02 order of growth
 
Complexity analysis in Algorithms
Complexity analysis in AlgorithmsComplexity analysis in Algorithms
Complexity analysis in Algorithms
 
Presentation on binary search, quick sort, merge sort and problems
Presentation on binary search, quick sort, merge sort  and problemsPresentation on binary search, quick sort, merge sort  and problems
Presentation on binary search, quick sort, merge sort and problems
 
asymptotic analysis and insertion sort analysis
asymptotic analysis and insertion sort analysisasymptotic analysis and insertion sort analysis
asymptotic analysis and insertion sort analysis
 
Unit6 C
Unit6 C Unit6 C
Unit6 C
 
Intro to Sorting + Insertion Sort
Intro to Sorting + Insertion SortIntro to Sorting + Insertion Sort
Intro to Sorting + Insertion Sort
 
Lecture 3 insertion sort and complexity analysis
Lecture 3   insertion sort and complexity analysisLecture 3   insertion sort and complexity analysis
Lecture 3 insertion sort and complexity analysis
 
Quick sort Algorithm Discussion And Analysis
Quick sort Algorithm Discussion And AnalysisQuick sort Algorithm Discussion And Analysis
Quick sort Algorithm Discussion And Analysis
 
Lecture 5 6_7 - divide and conquer and method of solving recurrences
Lecture 5 6_7 - divide and conquer and method of solving recurrencesLecture 5 6_7 - divide and conquer and method of solving recurrences
Lecture 5 6_7 - divide and conquer and method of solving recurrences
 
Lecture 4 asymptotic notations
Lecture 4   asymptotic notationsLecture 4   asymptotic notations
Lecture 4 asymptotic notations
 
Unit i basic concepts of algorithms
Unit i basic concepts of algorithmsUnit i basic concepts of algorithms
Unit i basic concepts of algorithms
 
Merge sort and quick sort
Merge sort and quick sortMerge sort and quick sort
Merge sort and quick sort
 
Performance analysis(Time & Space Complexity)
Performance analysis(Time & Space Complexity)Performance analysis(Time & Space Complexity)
Performance analysis(Time & Space Complexity)
 
Analysis of algorithn class 2
Analysis of algorithn class 2Analysis of algorithn class 2
Analysis of algorithn class 2
 
Design & Analysis of Algorithms Lecture Notes
Design & Analysis of Algorithms Lecture NotesDesign & Analysis of Algorithms Lecture Notes
Design & Analysis of Algorithms Lecture Notes
 
Sorting
SortingSorting
Sorting
 
Analysis of algorithm
Analysis of algorithmAnalysis of algorithm
Analysis of algorithm
 
Fundamentals of the Analysis of Algorithm Efficiency
Fundamentals of the Analysis of Algorithm EfficiencyFundamentals of the Analysis of Algorithm Efficiency
Fundamentals of the Analysis of Algorithm Efficiency
 
3.8 quick sort
3.8 quick sort3.8 quick sort
3.8 quick sort
 

Similar to 9.Sorting & Searching

Class13_Quicksort_Algorithm.pdf
Class13_Quicksort_Algorithm.pdfClass13_Quicksort_Algorithm.pdf
Class13_Quicksort_Algorithm.pdfAkashSingh625550
 
jn;lm;lkm';m';;lmppt of data structure.pdf
jn;lm;lkm';m';;lmppt of data structure.pdfjn;lm;lkm';m';;lmppt of data structure.pdf
jn;lm;lkm';m';;lmppt of data structure.pdfVinayNassa3
 
Data structures and algorithms
Data structures and algorithmsData structures and algorithms
Data structures and algorithmsJulie Iskander
 
Array operations
Array operationsArray operations
Array operationsRazzaaa
 
Algorithms - "Chapter 2 getting started"
Algorithms - "Chapter 2 getting started"Algorithms - "Chapter 2 getting started"
Algorithms - "Chapter 2 getting started"Ra'Fat Al-Msie'deen
 
Algorithms & Complexity Calculation
Algorithms & Complexity CalculationAlgorithms & Complexity Calculation
Algorithms & Complexity CalculationAkhil Kaushik
 
Design and Analysis of Algorithms Lecture Notes
Design and Analysis of Algorithms Lecture NotesDesign and Analysis of Algorithms Lecture Notes
Design and Analysis of Algorithms Lecture NotesSreedhar Chowdam
 
Sorting and hashing concepts
Sorting and hashing conceptsSorting and hashing concepts
Sorting and hashing conceptsLJ Projects
 
Sorting and hashing concepts
Sorting and hashing conceptsSorting and hashing concepts
Sorting and hashing conceptsLJ Projects
 
2. Asymptotic Notations and Complexity Analysis.pptx
2. Asymptotic Notations and Complexity Analysis.pptx2. Asymptotic Notations and Complexity Analysis.pptx
2. Asymptotic Notations and Complexity Analysis.pptxRams715121
 
Data structure and algorithm All in One
Data structure and algorithm All in OneData structure and algorithm All in One
Data structure and algorithm All in Onejehan1987
 
quick sort by deepak.pptx
quick sort by deepak.pptxquick sort by deepak.pptx
quick sort by deepak.pptxDeepakM509554
 
Tri Merge Sorting Algorithm
Tri Merge Sorting AlgorithmTri Merge Sorting Algorithm
Tri Merge Sorting AlgorithmAshim Sikder
 
Lecture 11.2 : sorting
Lecture 11.2 :  sortingLecture 11.2 :  sorting
Lecture 11.2 : sortingVivek Bhargav
 
Introduction to Algorithms
Introduction to AlgorithmsIntroduction to Algorithms
Introduction to Algorithmspppepito86
 
Algorithm Complexity and Main Concepts
Algorithm Complexity and Main ConceptsAlgorithm Complexity and Main Concepts
Algorithm Complexity and Main ConceptsAdelina Ahadova
 

Similar to 9.Sorting & Searching (20)

Class13_Quicksort_Algorithm.pdf
Class13_Quicksort_Algorithm.pdfClass13_Quicksort_Algorithm.pdf
Class13_Quicksort_Algorithm.pdf
 
jn;lm;lkm';m';;lmppt of data structure.pdf
jn;lm;lkm';m';;lmppt of data structure.pdfjn;lm;lkm';m';;lmppt of data structure.pdf
jn;lm;lkm';m';;lmppt of data structure.pdf
 
Data Structures 6
Data Structures 6Data Structures 6
Data Structures 6
 
Data structures and algorithms
Data structures and algorithmsData structures and algorithms
Data structures and algorithms
 
Array operations
Array operationsArray operations
Array operations
 
Algorithms - "Chapter 2 getting started"
Algorithms - "Chapter 2 getting started"Algorithms - "Chapter 2 getting started"
Algorithms - "Chapter 2 getting started"
 
Algorithms & Complexity Calculation
Algorithms & Complexity CalculationAlgorithms & Complexity Calculation
Algorithms & Complexity Calculation
 
Unit 7 sorting
Unit 7   sortingUnit 7   sorting
Unit 7 sorting
 
Searching Algorithms
Searching AlgorithmsSearching Algorithms
Searching Algorithms
 
Design and Analysis of Algorithms Lecture Notes
Design and Analysis of Algorithms Lecture NotesDesign and Analysis of Algorithms Lecture Notes
Design and Analysis of Algorithms Lecture Notes
 
Sorting and hashing concepts
Sorting and hashing conceptsSorting and hashing concepts
Sorting and hashing concepts
 
Sorting and hashing concepts
Sorting and hashing conceptsSorting and hashing concepts
Sorting and hashing concepts
 
2. Asymptotic Notations and Complexity Analysis.pptx
2. Asymptotic Notations and Complexity Analysis.pptx2. Asymptotic Notations and Complexity Analysis.pptx
2. Asymptotic Notations and Complexity Analysis.pptx
 
Data structure and algorithm All in One
Data structure and algorithm All in OneData structure and algorithm All in One
Data structure and algorithm All in One
 
quick sort by deepak.pptx
quick sort by deepak.pptxquick sort by deepak.pptx
quick sort by deepak.pptx
 
Tri Merge Sorting Algorithm
Tri Merge Sorting AlgorithmTri Merge Sorting Algorithm
Tri Merge Sorting Algorithm
 
Lecture 11.2 : sorting
Lecture 11.2 :  sortingLecture 11.2 :  sorting
Lecture 11.2 : sorting
 
Introduction to Algorithms
Introduction to AlgorithmsIntroduction to Algorithms
Introduction to Algorithms
 
DSA
DSADSA
DSA
 
Algorithm Complexity and Main Concepts
Algorithm Complexity and Main ConceptsAlgorithm Complexity and Main Concepts
Algorithm Complexity and Main Concepts
 

More from Mandeep Singh

4. Queues in Data Structure
4. Queues in Data Structure4. Queues in Data Structure
4. Queues in Data StructureMandeep Singh
 
Stacks in DATA STRUCTURE
Stacks in DATA STRUCTUREStacks in DATA STRUCTURE
Stacks in DATA STRUCTUREMandeep Singh
 
2. Array in Data Structure
2. Array in Data Structure2. Array in Data Structure
2. Array in Data StructureMandeep Singh
 
1. Data structures introduction
1. Data structures introduction1. Data structures introduction
1. Data structures introductionMandeep Singh
 
Standard Template Library (STL) in Object Oriented Programming
Standard Template Library (STL) in Object Oriented ProgrammingStandard Template Library (STL) in Object Oriented Programming
Standard Template Library (STL) in Object Oriented ProgrammingMandeep Singh
 

More from Mandeep Singh (11)

8. Hash table
8. Hash table8. Hash table
8. Hash table
 
7. Spanning trees
7. Spanning trees7. Spanning trees
7. Spanning trees
 
6. Graphs
6. Graphs6. Graphs
6. Graphs
 
5.Linked list
5.Linked list 5.Linked list
5.Linked list
 
4. Queues in Data Structure
4. Queues in Data Structure4. Queues in Data Structure
4. Queues in Data Structure
 
Stacks in DATA STRUCTURE
Stacks in DATA STRUCTUREStacks in DATA STRUCTURE
Stacks in DATA STRUCTURE
 
2. Array in Data Structure
2. Array in Data Structure2. Array in Data Structure
2. Array in Data Structure
 
1. Data structures introduction
1. Data structures introduction1. Data structures introduction
1. Data structures introduction
 
Standard Template Library (STL) in Object Oriented Programming
Standard Template Library (STL) in Object Oriented ProgrammingStandard Template Library (STL) in Object Oriented Programming
Standard Template Library (STL) in Object Oriented Programming
 
Ip6 tables in linux
Ip6 tables in linuxIp6 tables in linux
Ip6 tables in linux
 
Iptables in linux
Iptables in linuxIptables in linux
Iptables in linux
 

Recently uploaded

mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docxPoojaSen20
 
Hybridoma Technology ( Production , Purification , and Application )
Hybridoma Technology  ( Production , Purification , and Application  ) Hybridoma Technology  ( Production , Purification , and Application  )
Hybridoma Technology ( Production , Purification , and Application ) Sakshi Ghasle
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxiammrhaywood
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeThiyagu K
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxmanuelaromero2013
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionSafetyChain Software
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactPECB
 
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxContemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxRoyAbrique
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdfQucHHunhnh
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptxVS Mahajan Coaching Centre
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxNirmalaLoungPoorunde1
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfJayanti Pande
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphThiyagu K
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdfQucHHunhnh
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)eniolaolutunde
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...Marc Dusseiller Dusjagr
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactdawncurless
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfchloefrazer622
 

Recently uploaded (20)

mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docx
 
Hybridoma Technology ( Production , Purification , and Application )
Hybridoma Technology  ( Production , Purification , and Application  ) Hybridoma Technology  ( Production , Purification , and Application  )
Hybridoma Technology ( Production , Purification , and Application )
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and Mode
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptx
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory Inspection
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global Impact
 
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxContemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 
Staff of Color (SOC) Retention Efforts DDSD
Staff of Color (SOC) Retention Efforts DDSDStaff of Color (SOC) Retention Efforts DDSD
Staff of Color (SOC) Retention Efforts DDSD
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptx
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdf
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot Graph
 
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdfTataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impact
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdf
 

9.Sorting & Searching

  • 2. Searching Internal Search The search in which the whole list resides in the main memory is called internal search. External Search The search in which the whole list resides in the Secondary memory is called external search.
  • 3. Types of searching Algorithm • Linear or Sequential searching • Binary searching
  • 4. Algorithm For Linear Search LINEAR(DATA ,N,ITEM,LOC) 1.Set K:=1 and LOC := 0. 2.Repeat Steps 3 and 4 while LOC = 0 and K<=N. 3.If ITEM = DATA[K] ,then Set LOC:= K. 4.Set K:=K+1. 5.If LOC = 0,then: Write: ITEM is not in the array DATA. Else: Write: LOC is the location of ITEM. 6.Exit.
  • 5. Advantages • Not Expensive. • List/Array may or may not be sorted. Disadvantages • Less Efficient. • Time consuming.
  • 6. Algorithm For Binary Search BINARY(DATA , LB , UB, ITEM , LOC) 1. Set BEG:= LB, END:=UB and MID = INT((BEG+END)/2). 2. Repeat Steps 3 and 4 while BEG<=END and DATA[MID]!=ITEM. 3. If ITEM< DATA[MID] ,then: Set END := MID-1. Else: Set BEG := MID+1. 4. Set MID := INT((BEG+END)/2).
  • 7. Algo. Cont. 5. If DATA[MID]=ITEM, then: Set LOC:= MID. Else: Set LOC:= NULL. 6. Exit.
  • 8. Advantages • Extremely Efficient • Less Time Consuming Disadvantages • Expensive • List/Array may be sorted.
  • 9. Introduction to Sorting • Sorting: An operation that arranges items into groups according to specified criterion. A = { 3 1 6 2 1 3 4 5 9 0 } A = { 0 1 1 2 3 3 4 5 6 9 }
  • 10. Why Sort and Examples Consider: • Sorting Books in Library (Dewey system) • Sorting Individuals by Height (Feet and Inches) • Sorting Movies in Blockbuster (Alphabetical) • Sorting Numbers (Sequential)
  • 11. Types of Sorting Algorithms There are many different types of sorting algorithms, but the primary ones are: • Bubble Sort • Selection Sort • Insertion Sort • Merge Sort • Quick Sort • Radix Sort • Heap Sort
  • 12. Complexity • Most of the primary sorting algorithms run on different space and time complexity. • Time Complexity is defined to be the time the computer takes to run a program (or algorithm in our case). • Space complexity is defined to be the amount of memory the computer needs to run a program.
  • 13. Complexity (cont.) Complexity in general, measures the algorithms efficiency in internal factors such as the time needed to run an algorithm. External Factors (not related to complexity): •Size of the input of the algorithm •Speed of the Computer •Quality of the Compiler
  • 14. O(n), Ω(n), & Θ(n) • An algorithm or function T(n) is O(f(n)) whenever T(n)'s rate of growth is less than or equal to f(n)'s rate. • An algorithm or function T(n) is Ω(f(n)) whenever T(n)'s rate of growth is greater than or equal to f(n)'s rate. • An algorithm or function T(n) is Θ(f(n)) if and only if the rate of growth of T(n) is equal to f(n).
  • 15. 10 Common Big-Oh’s Time complexity Example O(1) constant Adding to the front of a linked list O(log N) log Finding an entry in a sorted array O(N) linear Finding an entry in an unsorted array O(N log N) n-log-n Sorting n items by ‘divide-and-conquer’ O(N2 ) quadratic Shortest path between two nodes in a graph O(N3 ) cubic Simultaneous linear equations (Binary) Finding 8: 9 50 22 21 8 5 1 (Linear) Finding 8: 9 50 22 21 8 5 1Front Initial: Final:63 http://www.cs.sjsu.edu/faculty/lee/cs146/23FL3Complexity.ppt
  • 16. Big-Oh to Primary Sorts ● Bubble Sort = n² ● Selection Sort = n² ● Insertion Sort = n² ● Merge Sort = n log(n) ●Quick Sort = n log(n)
  • 17. Time Efficiency • How do we improve the time efficiency of a program? • The 90/10 Rule –90% of the execution time of a program is spent in –executing 10% of the code • So, how do we locate the critical 10%? – software metrics tools – global counters to locate bottlenecks (loop executions, function calls)
  • 18. Time Efficiency Improvements • Possibilities (some better than others!) • Move code out of loops that does not belong there (just good programming!) • Remove any unnecessary I/O operations (I/O operations are expensive time-wise) • Code so that the compiled code is more efficient •Moral - Choose the most appropriate algorithm(s) BEFORE program implementation
  • 20. Selection Sort MIN(A,K,N,LOC) 1. Set MIN = A[K] and LOC = K 2. Repeat for J=K+1, K+2 ……… N If MIN>A[J], then Set MIN = A[J] and LOC = J End of Loop 3. Return
  • 21. Selection Sort SELECTION (A,N) 1. Repeat steps 2 and 3 for K=1, 2 ……… N-1 2. Call MIN(A,K,N,LOC) 3. Set TEMP = A[K] A[K] = A[LOC] A[LOC] = TEMP End of Step 1 Loop 4. Exit
  • 22. Complexity of the Selection Sort • Worst Case – O(n2) • Average Case – O(n2)
  • 25. Insertion Sort INSERTION (A,N) 1. Set A[0] = - ∞ 2. Repeat Steps 3 to 5 for K = 2,3,….N 3. Set TEMP = A[K] and PTR = K-1 4. Repeat while TEMP<A[PTR] 1. Set A[PTR+1] = A[PTR] 2. Set PTR = PTR – 1 End of Loop 5. Set A[PTR+1] = TEMP End of Step 2 Loop 6. Return
  • 26. Complexity of the Insertion Sort • Worst Case – O(n2) • Average Case – O(n2)
  • 28. Algorithm for BUBBLE SORT BUBBLE(DATA , N) 1.Repeat Steps 2 and 3 for K=1 to N-1. 2.Set PTR := 1. // Initialize pass pointer PTR 3.Repeat while PTR<=N-K. a) If DATA[PTR]>DATA[PTR+1],then Interchange DATA[PTR] and DATA[PTR+1] b) Set PTR:= PTR+1 4. Exit.
  • 32. MERGE SORT MERGE_SORT (A, BEG, END) 1. IF BEG<ENG SET MID=(BEG+END)/2 CALL MERGE_SORT (A, BEG, MID) CALL MERGE_SORT (A, MID+1, END) MERGE(A, BEG, MID, END) 2. END
  • 33. MERGE(A, BEG, MID, END) 1. SET I = BEG, J=MID+1, INDEX=0 2. REPEAT WHILE (I<=MID) AND (J<=END) IF A[I]<A[J], THEN SET TEMP [INDEX] = A[I] SET I=I+1 ELSE SET TEMP [INDEX]=A[J] SET J=J+1 SET INDEX = INDEX +1
  • 34. 3. IF I>MID THEN REPEAT WHILE J<=END SET TEMP [INDEX]=A[J] SET INDEX=INDEX+1 SET J=J+1 ELSE REPEAT WHILE I<=MID SET TEMP[INDEX]=A[I] SET INDEX = INDEX +1 SET I=I+1
  • 35. 4. SET K=0 5. REPEAT WHILE K<INDEX SET A[K]=TEMP[K] SET K=K+1 6. END
  • 36. QUICKSORT Starting with first element of list do the operations 1. Compare from right to find element less than selected and interchange 2. Compare from left to find element greater than selected and interchange 44,33,11,55,77,90,40,60,33,22,88,66 22,33,11,55,77,90,40,60,99,44,88,66 22,33,11,44,77,90,40,60,99,55,88,66 22,33,11,40,77,90,44,60,99,55,88,66 22,33,11,40,44,90,77,60,99,55,88,66 22,33,11,40,44,90,77,60,99,55,88,66 Two Sublists are created: Before 44 and After 44
  • 37. 37 Quick Sort Algorithm QUICK (A, N, BEG, END, LOC) 1. [Initialize] Set LEFT= BEG, RIGHT=END and LOC=BEG 2. [Scan from right to left] a) Repeat while A[LOC]<=A[RIGHT] and LOC != RIGHT RIGHT=RIGHT-1 [End of loop] b) If LOC=RIGHT then : Return c) If A[LOC]>A[RIGHT] then i) Interchange A[LOC] and A[RIGHT] ii) Set LOC=RIGHT iii) Go to step 3 [End of If structure]
  • 38. 3. [Scan from left to right] a) Repeat while A[LEFT]<=A[LOC] and LEFT!=LOC LEFT=LEFT+1 [End of loop] b) If LOC=LEFT, then Return c) If A[LEFT]>A[LOC], then i) Interchange A[LEFT] and A[LOC] ii) Set LOC=LEFT iii) Goto step 2 [End of If structure] 38
  • 39. (QuickSort) This algorithm sorts an array A with N elements. 1. TOP=NULL 2. If N>1 then TOP=TOP+1, LOWER[1]=1, UPPER[1]=N 3. Repeat Steps 4 to 7 while TOP!=NULL 4. Set BEG=LOWER[TOP], END=UPPER[TOP] TOP=TOP-1 5. Call QUICK(A, N, BEG, END, LOC) 6. If BEG<LOC-1 then TOP=TOP+1, LOWER[TOP]=BEG, UPPER[TOP]=LOC-1 [End of If structure] 7. If LOC+1<END then TOP=TOP+1, LOWER[TOP]=LOC+1, UPPER[TOP]=END [End of If Structure] [End of Step 3 loop] 8. Exit 39
  • 42. Radix Sort (or Bucket Sort) • It is a non comparative integer sorting algorithm • It sorts data with integer keys by grouping keys by the individual digits which share the same significant position and value. • A positional notation is required, but because integers can represent strings of characters (e.g., names or dates) and specially formatted floating point numbers, Radix sort is not limited to integers.
  • 43. Radix Sort Algorithm Let A be an array with N elements in the memory • Find the largest element of the array • Find the total no. of digits ‘NUM’ in the largest element • Repeat Steps 4, 5 for PASS = 1 to NUM • Initialize buckets (0 to 9 for numbers, A to Z for Characters) For i = 0 to (N-1) Set DIGIT = Obtain digit number PASS of A [i] Put A [i] in bucket number DIGIT End of for loop 5. Collect all numbers from the bucket in order 6. Exit