SlideShare a Scribd company logo
Introduc)on to Searching
and Sor)ng Algorithms
Chapter 1
Searching Algorithms
• A searching algorithm is a method of loca3ng a specific
item in a collec3on of data
• For simplicity, let’s assume that our data is an array of 𝑛
posi3ve integers
– It may or may not contain duplicate values
• Consider two algorithms for searching the contents of
an array:
– The linear search
– The binary search
2
• The linear search is a very simple algorithm. Some3mes
it’s called a sequen&al search
• Star3ng with the first element, the algorithm uses a loop
to sequen3ally step through a given array
• It compares each element with the search key and stops
when either
– a match is encountered (successful search), or
– the end of the array is encountered without finding a match
(unsuccessful search)
3
Searching Algorithms: Linear Search
4
i = 0;
while (i < n && a[i] != k)
i++;
return (i < n);
Pseudo-code
5
a[n] = k;
i = 0;
while (a[i] != k)
i++;
return (i < n);
Pseudo-code
sentinel
• Advantages:
– It’s simple, easy to understand and implement
– It doesn’t require the data in the array to be stored in any
par@cular order
• Disadvantage:
– It’s inefficient
6
Searching Algorithms: Linear Search
• How can we improve linear search if a given array is
known to be sorted (say, in ascending order)?
• Searching in such an array can be stopped as soon as
an element greater than or equal to the search key is
encountered
7
Searching Algorithms: Linear Search
8
i = 0;
while (i < n && a[i] < k)
i++;
return (i < n && a[i] == k);
Pseudo-code
9
a[n] = k + 1;
i = 0;
while (a[i] < k)
i++;
return (a[i] == k);
Pseudo-code
• Given a sorted array, binary search is always our choice
• The binary search is a clever algorithm that is much
more efficient than the linear search
10
Searching Algorithms: Binary Search
• It starts with the element in the middle: 𝑎 𝑚
– If 𝑎 𝑚 = 𝑘: 👌
– If 𝑎 𝑚 > 𝑘: the desired value will be found somewhere in
the le# half of the array
➡ The right half of the array is eleminated from searching
– If 𝑎 𝑚 < 𝑘: the desired value will be found somewhere in
the right half of the array
➡ The le# half of the array is eleminated from searching
• This process con3nues un3l either the desired value is
found or there are no more elements to test 11
Searching Algorithms: Binary Search
12
left = 0, right = n – 1;
while (left ≤ right) {
middle = (left + right) / 2;
if (a[middle] == k)
return true;
else
if (k < a[middle])
right = middle – 1;
else
left = middle + 1;
}
return false;
Pseudo-code
13
Searching Algorithms: Binary Search
• Advantages:
– The binary search is much more efficient than the linear
search
– How to evaluate the efficiency of the binary search?
• Disadvantage:
– The input array must be sorted
14
Searching Algorithms: Case Study
Finding both the smallest and largest values in an array of
size 𝑛 simultaneously
small = large = a[0];
for (i = 1; i < n; i++) {
if (small > a[i]) small = a[i];
if (large < a[i]) large = a[i];
}
small = large = a[0];
for (i = 1; i < n; i++)
if (small > a[i]) small = a[i];
else
if (large < a[i]) large = a[i];
Sor:ng Algorithms
• OOen the data in an array must be sorted in some order
• This sec3on will introduce 4 basic sor3ng algorithms:
– The bubble sort
– The selec@on sort
– The inser@on sort
– The interchange sort
15
Sor:ng Algorithms: Bubble Sort
• In essence, this algorithm compares adjacent elements
of the array and exchanges them if they are out of order
16
Bubble Sort: Example
17
Bubble Sort: Pseudo-code
18
for (i = 1; i < n; i++)
for (j = n - 1; j ≥ i; j--)
if (a[j] < a[j - 1])
swap(a[j], a[j - 1]);
Sor:ng Algorithms: Selec:on Sort
• The selec3on sort moves elements immediately to their
final posi3on in the sorted array
19
Selec:on Sort: Example
20
Selec:on Sort: Pseudo-code
21
for (i = 0; i < n – 1; i++) {
minIndex = i;
minValue = a[i];
for (j = i + 1; j < n; j++)
if (a[j] < minValue) {
minIndex = j;
minValue = a[j];
}
a[minIndex] = a[i];
a[i] = minValue;
}
Sor:ng Algorithms: Inser:on Sort
• The inser3on sort works in a slightly different way
• The given array is split into two parts:
– The leE part is always a sorted subarray
– The right part is an unsorted subarray
• While the right part is not empty, the leO-most element
of this part is picked up and inserted back into the leO
part such that this sorted subarray is one element larger
– How to insert the leE-most element of the right part to the
right posi@on in the leE part?
22
Inser:on Sort: Algorithm
• Let the leO-most element of the right part be 𝑣. It will
be checked against those in the leO part
– If the elements in the leE part are greater than 𝑣, they will be
shiEed to the right one posi@on
– If an element in the leE part (𝑖) is less than or equal to 𝑣, or
(𝑖𝑖) the end of the leE part is reached, 𝑣 can be inserted to
the right posi@on
• At first, the algorithm assumes that the leO part
contains only one element
23
Inser:on Sort: Example
24
Inser:on Sort: Pseudo-code
25
for (i = 1; i < n; i++) {
v = a[i];
j = i – 1;
while (j ≥ 0 && a[j] > v) {
a[j + 1] = a[j];
j--;
}
a[j + 1] = v;
}
At first, the leE part contains only one element
Sor:ng Algorithms: Interchange Sort
• Similar to the selec3on sort, this algorithm puts the
smallest value in the first posi3on, the second smallest
value in the next posi3on and so on
26
Interchange Sort: Example
27
Interchange Sort: Pseudo-code
28
for (i = 0; i < n – 1; i++)
for (j = i + 1; j < n; j++)
if (a[i] > a[j])
swap(a[i], a[j]);
29
Basic Sor:ng Algorithms: Conclusions
• Advantages
– They are simple and easy to implement
– They are in-place algorithms, so the space requirement is
minimal
– They are useful only when sor@ng an array of few elements
– The Bubble sort and the Interchange sort are suitable for
academic teaching but not for real-life applica@ons
– The Selec9on sort tends to minimize data movements
– The Inser9on sort can also be useful when input array is
almost sorted
30
Basic Sor:ng Algorithms: Conclusions
• Disadvantage
– They do not deal well with an array containing a huge number
of elements
31
Sor:ng Algorithms: Case Study
Develop an efficient in-place algorithm that par33ons an
array 𝑎 in even and odd numbers
The algorithm must terminate with 𝑎 containing all its
even elements preceding all its odd elements
In addi3on, even elements are in ascending order and
odd elements are in descending order
tạo thuật toán :
1 mảng lưu các số
số chẵn đứng trước số lẻ
số chẵn xếp tăng dần, số lẻ xếp giảm dần
32
Sor:ng Algorithms: Case Study
Given a two-dimensional array of the size 3×3 containing
posi3ve integers
Arrange them so that all numbers in each row, in each
column and in both diagonals are in ascending order

More Related Content

Similar to Chapter 1 - Introduction to Searching and Sorting Algorithms - Student.pdf (20)

PPTX
UNIT V Searching Sorting Hashing Techniques [Autosaved].pptx
VISWANATHAN R V
 
PPTX
Unit vii sorting
Tribhuvan University
 
PPTX
Data Structures Unit 2 FINAL presentation.pptx
dilipd20
 
PPTX
Algorithms and Data Structures for Sorting Numerical Data
Pratik Parmar
 
PPTX
Unit 7 sorting
Dabbal Singh Mahara
 
PDF
DSA Lec 5+6(Search+Sort) (1).pdf
MustafaJutt4
 
PPTX
DSA_chapter and chapter 3 _03_Sorting Algorithms.pptx
tahliildhoore54
 
PPT
Chapter 11 - Sorting and Searching
Eduardo Bergavera
 
PPTX
Lect-2.pptx
mrizwan38
 
PPT
21-algorithms (1).ppt
DaniloMislosAlbay
 
PPT
Searching Sorting-SELECTION ,BUBBBLE.ppt
kunalpatil5661
 
PPTX
Searching and Sorting Algorithms in Data Structures
poongothai11
 
PPTX
Algorithm analysis (All in one)
jehan1987
 
PPTX
Algorithms
WaqarzadAa
 
PPTX
Unit viii searching and hashing
Tribhuvan University
 
PPTX
Chapter3.pptx
ASMAALWADEE2
 
PPTX
what is sorting algorithm and implementation.pptx
TanaTech
 
PPT
21-algorithms.ppt
ashwinraiyani1
 
PPT
Algorithm, Pseudocode and Flowcharting in C++
Johnny Jean Tigas
 
UNIT V Searching Sorting Hashing Techniques [Autosaved].pptx
VISWANATHAN R V
 
Unit vii sorting
Tribhuvan University
 
Data Structures Unit 2 FINAL presentation.pptx
dilipd20
 
Algorithms and Data Structures for Sorting Numerical Data
Pratik Parmar
 
Unit 7 sorting
Dabbal Singh Mahara
 
DSA Lec 5+6(Search+Sort) (1).pdf
MustafaJutt4
 
DSA_chapter and chapter 3 _03_Sorting Algorithms.pptx
tahliildhoore54
 
Chapter 11 - Sorting and Searching
Eduardo Bergavera
 
Lect-2.pptx
mrizwan38
 
21-algorithms (1).ppt
DaniloMislosAlbay
 
Searching Sorting-SELECTION ,BUBBBLE.ppt
kunalpatil5661
 
Searching and Sorting Algorithms in Data Structures
poongothai11
 
Algorithm analysis (All in one)
jehan1987
 
Algorithms
WaqarzadAa
 
Unit viii searching and hashing
Tribhuvan University
 
Chapter3.pptx
ASMAALWADEE2
 
what is sorting algorithm and implementation.pptx
TanaTech
 
21-algorithms.ppt
ashwinraiyani1
 
Algorithm, Pseudocode and Flowcharting in C++
Johnny Jean Tigas
 

Recently uploaded (20)

DOCX
brigada_PROGRAM_25.docx the boys white house
RonelNebrao
 
PDF
TCU EVALUATION FACULTY TCU Taguig City 1st Semester 2017-2018
MELJUN CORTES
 
PDF
Microsoft Power BI - Advanced Certificate for Business Intelligence using Pow...
Prasenjit Debnath
 
PDF
IT GOVERNANCE 4-2 - Information System Security (1).pdf
mdirfanuddin1322
 
PDF
Exploiting the Low Volatility Anomaly: A Low Beta Model Portfolio for Risk-Ad...
Bradley Norbom, CFA
 
PPTX
Mynd company all details what they are doing a
AniketKadam40952
 
PDF
5991-5857_Agilent_MS_Theory_EN (1).pdf. pdf
NohaSalah45
 
PPTX
RESEARCH-FINAL-GROUP-3, about the final .pptx
gwapokoha1
 
PPTX
PPT2 W1L2.pptx.........................................
palicteronalyn26
 
PPTX
covid 19 data analysis updates in our municipality
RhuAyungon1
 
PDF
Predicting Titanic Survival Presentation
praxyfarhana
 
PDF
Datàaaaaaaaaaengineeeeeeeeeeeeeeeeeeeeeee
juadsr96
 
PDF
A Web Repository System for Data Mining in Drug Discovery
IJDKP
 
PDF
ilide.info-tg-understanding-culture-society-and-politics-pr_127f984d2904c57ec...
jed P
 
PPTX
MENU-DRIVEN PROGRAM ON ARUNACHAL PRADESH.pptx
manvi200807
 
PDF
SaleServicereport and SaleServicereport
2251330007
 
PPTX
Model Evaluation & Visualisation part of a series of intro modules for data ...
brandonlee626749
 
PPTX
Presentation.pptx hhgihyugyygyijguuffddfffffff
abhiruppal2007
 
PDF
Blood pressure (3).pdfbdbsbsbhshshshhdhdhshshs
hernandezemma379
 
brigada_PROGRAM_25.docx the boys white house
RonelNebrao
 
TCU EVALUATION FACULTY TCU Taguig City 1st Semester 2017-2018
MELJUN CORTES
 
Microsoft Power BI - Advanced Certificate for Business Intelligence using Pow...
Prasenjit Debnath
 
IT GOVERNANCE 4-2 - Information System Security (1).pdf
mdirfanuddin1322
 
Exploiting the Low Volatility Anomaly: A Low Beta Model Portfolio for Risk-Ad...
Bradley Norbom, CFA
 
Mynd company all details what they are doing a
AniketKadam40952
 
5991-5857_Agilent_MS_Theory_EN (1).pdf. pdf
NohaSalah45
 
RESEARCH-FINAL-GROUP-3, about the final .pptx
gwapokoha1
 
PPT2 W1L2.pptx.........................................
palicteronalyn26
 
covid 19 data analysis updates in our municipality
RhuAyungon1
 
Predicting Titanic Survival Presentation
praxyfarhana
 
Datàaaaaaaaaaengineeeeeeeeeeeeeeeeeeeeeee
juadsr96
 
A Web Repository System for Data Mining in Drug Discovery
IJDKP
 
ilide.info-tg-understanding-culture-society-and-politics-pr_127f984d2904c57ec...
jed P
 
MENU-DRIVEN PROGRAM ON ARUNACHAL PRADESH.pptx
manvi200807
 
SaleServicereport and SaleServicereport
2251330007
 
Model Evaluation & Visualisation part of a series of intro modules for data ...
brandonlee626749
 
Presentation.pptx hhgihyugyygyijguuffddfffffff
abhiruppal2007
 
Blood pressure (3).pdfbdbsbsbhshshshhdhdhshshs
hernandezemma379
 
Ad

Chapter 1 - Introduction to Searching and Sorting Algorithms - Student.pdf

  • 1. Introduc)on to Searching and Sor)ng Algorithms Chapter 1
  • 2. Searching Algorithms • A searching algorithm is a method of loca3ng a specific item in a collec3on of data • For simplicity, let’s assume that our data is an array of 𝑛 posi3ve integers – It may or may not contain duplicate values • Consider two algorithms for searching the contents of an array: – The linear search – The binary search 2
  • 3. • The linear search is a very simple algorithm. Some3mes it’s called a sequen&al search • Star3ng with the first element, the algorithm uses a loop to sequen3ally step through a given array • It compares each element with the search key and stops when either – a match is encountered (successful search), or – the end of the array is encountered without finding a match (unsuccessful search) 3 Searching Algorithms: Linear Search
  • 4. 4 i = 0; while (i < n && a[i] != k) i++; return (i < n); Pseudo-code
  • 5. 5 a[n] = k; i = 0; while (a[i] != k) i++; return (i < n); Pseudo-code sentinel
  • 6. • Advantages: – It’s simple, easy to understand and implement – It doesn’t require the data in the array to be stored in any par@cular order • Disadvantage: – It’s inefficient 6 Searching Algorithms: Linear Search
  • 7. • How can we improve linear search if a given array is known to be sorted (say, in ascending order)? • Searching in such an array can be stopped as soon as an element greater than or equal to the search key is encountered 7 Searching Algorithms: Linear Search
  • 8. 8 i = 0; while (i < n && a[i] < k) i++; return (i < n && a[i] == k); Pseudo-code
  • 9. 9 a[n] = k + 1; i = 0; while (a[i] < k) i++; return (a[i] == k); Pseudo-code
  • 10. • Given a sorted array, binary search is always our choice • The binary search is a clever algorithm that is much more efficient than the linear search 10 Searching Algorithms: Binary Search
  • 11. • It starts with the element in the middle: 𝑎 𝑚 – If 𝑎 𝑚 = 𝑘: 👌 – If 𝑎 𝑚 > 𝑘: the desired value will be found somewhere in the le# half of the array ➡ The right half of the array is eleminated from searching – If 𝑎 𝑚 < 𝑘: the desired value will be found somewhere in the right half of the array ➡ The le# half of the array is eleminated from searching • This process con3nues un3l either the desired value is found or there are no more elements to test 11 Searching Algorithms: Binary Search
  • 12. 12 left = 0, right = n – 1; while (left ≤ right) { middle = (left + right) / 2; if (a[middle] == k) return true; else if (k < a[middle]) right = middle – 1; else left = middle + 1; } return false; Pseudo-code
  • 13. 13 Searching Algorithms: Binary Search • Advantages: – The binary search is much more efficient than the linear search – How to evaluate the efficiency of the binary search? • Disadvantage: – The input array must be sorted
  • 14. 14 Searching Algorithms: Case Study Finding both the smallest and largest values in an array of size 𝑛 simultaneously small = large = a[0]; for (i = 1; i < n; i++) { if (small > a[i]) small = a[i]; if (large < a[i]) large = a[i]; } small = large = a[0]; for (i = 1; i < n; i++) if (small > a[i]) small = a[i]; else if (large < a[i]) large = a[i];
  • 15. Sor:ng Algorithms • OOen the data in an array must be sorted in some order • This sec3on will introduce 4 basic sor3ng algorithms: – The bubble sort – The selec@on sort – The inser@on sort – The interchange sort 15
  • 16. Sor:ng Algorithms: Bubble Sort • In essence, this algorithm compares adjacent elements of the array and exchanges them if they are out of order 16
  • 18. Bubble Sort: Pseudo-code 18 for (i = 1; i < n; i++) for (j = n - 1; j ≥ i; j--) if (a[j] < a[j - 1]) swap(a[j], a[j - 1]);
  • 19. Sor:ng Algorithms: Selec:on Sort • The selec3on sort moves elements immediately to their final posi3on in the sorted array 19
  • 21. Selec:on Sort: Pseudo-code 21 for (i = 0; i < n – 1; i++) { minIndex = i; minValue = a[i]; for (j = i + 1; j < n; j++) if (a[j] < minValue) { minIndex = j; minValue = a[j]; } a[minIndex] = a[i]; a[i] = minValue; }
  • 22. Sor:ng Algorithms: Inser:on Sort • The inser3on sort works in a slightly different way • The given array is split into two parts: – The leE part is always a sorted subarray – The right part is an unsorted subarray • While the right part is not empty, the leO-most element of this part is picked up and inserted back into the leO part such that this sorted subarray is one element larger – How to insert the leE-most element of the right part to the right posi@on in the leE part? 22
  • 23. Inser:on Sort: Algorithm • Let the leO-most element of the right part be 𝑣. It will be checked against those in the leO part – If the elements in the leE part are greater than 𝑣, they will be shiEed to the right one posi@on – If an element in the leE part (𝑖) is less than or equal to 𝑣, or (𝑖𝑖) the end of the leE part is reached, 𝑣 can be inserted to the right posi@on • At first, the algorithm assumes that the leO part contains only one element 23
  • 25. Inser:on Sort: Pseudo-code 25 for (i = 1; i < n; i++) { v = a[i]; j = i – 1; while (j ≥ 0 && a[j] > v) { a[j + 1] = a[j]; j--; } a[j + 1] = v; } At first, the leE part contains only one element
  • 26. Sor:ng Algorithms: Interchange Sort • Similar to the selec3on sort, this algorithm puts the smallest value in the first posi3on, the second smallest value in the next posi3on and so on 26
  • 28. Interchange Sort: Pseudo-code 28 for (i = 0; i < n – 1; i++) for (j = i + 1; j < n; j++) if (a[i] > a[j]) swap(a[i], a[j]);
  • 29. 29 Basic Sor:ng Algorithms: Conclusions • Advantages – They are simple and easy to implement – They are in-place algorithms, so the space requirement is minimal – They are useful only when sor@ng an array of few elements – The Bubble sort and the Interchange sort are suitable for academic teaching but not for real-life applica@ons – The Selec9on sort tends to minimize data movements – The Inser9on sort can also be useful when input array is almost sorted
  • 30. 30 Basic Sor:ng Algorithms: Conclusions • Disadvantage – They do not deal well with an array containing a huge number of elements
  • 31. 31 Sor:ng Algorithms: Case Study Develop an efficient in-place algorithm that par33ons an array 𝑎 in even and odd numbers The algorithm must terminate with 𝑎 containing all its even elements preceding all its odd elements In addi3on, even elements are in ascending order and odd elements are in descending order tạo thuật toán : 1 mảng lưu các số số chẵn đứng trước số lẻ số chẵn xếp tăng dần, số lẻ xếp giảm dần
  • 32. 32 Sor:ng Algorithms: Case Study Given a two-dimensional array of the size 3×3 containing posi3ve integers Arrange them so that all numbers in each row, in each column and in both diagonals are in ascending order