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

PPTX
Chapter-2.pptx
PPTX
Chapter 2. data structure and algorithm
PPT
search_sort_v1.pptgghghhhggggjjjjjjllllllllvbbbbbcfdsdfffg
PPT
search_sort search_sortsearch_sort search_sortsearch_sortsearch_sortsearch_sort
PPT
search_sort Search sortSearch sortSearch sortSearch sort
PPT
SEARCHING AND SORTING ALGORITHMS
PDF
L 14-ct1120
PPTX
sorting-160810203705.pptx
Chapter-2.pptx
Chapter 2. data structure and algorithm
search_sort_v1.pptgghghhhggggjjjjjjllllllllvbbbbbcfdsdfffg
search_sort search_sortsearch_sort search_sortsearch_sortsearch_sortsearch_sort
search_sort Search sortSearch sortSearch sortSearch sort
SEARCHING AND SORTING ALGORITHMS
L 14-ct1120
sorting-160810203705.pptx

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

PPTX
All Searching and Sorting Techniques in Data Structures
PPTX
Searching, Sorting and Hashing Techniques
PPTX
Searching,sorting
ODP
Data operatons & searching and sorting algorithms
PPTX
Different Searching and Sorting Methods.pptx
PPTX
sorting-160810203705.pptx
PPTX
LLL3 Searching & Sorting algorithms.pptx
PPTX
Chapter 3 - Data Structure and Algorithms.pptx
PPTX
Unit vii sorting
PPTX
Data Structure and algorithms for software
PPTX
Searching and sorting Techniques in Data structures
DOCX
Sorting
PPT
358 33 powerpoint-slides_14-sorting_chapter-14
PPTX
searching in data structure.pptx
PPSX
Data Structure and Algorithm Chapter 2.ppsx Chapter 2.ppsx
PPTX
UNIT V Searching Sorting Hashing Techniques [Autosaved].pptx
PPTX
UNIT V Searching Sorting Hashing Techniques [Autosaved].pptx
PPTX
Algorithm & data structures lec4&5
PPT
Insert Sort & Merge Sort Using C Programming
PDF
Sorting algorithms
All Searching and Sorting Techniques in Data Structures
Searching, Sorting and Hashing Techniques
Searching,sorting
Data operatons & searching and sorting algorithms
Different Searching and Sorting Methods.pptx
sorting-160810203705.pptx
LLL3 Searching & Sorting algorithms.pptx
Chapter 3 - Data Structure and Algorithms.pptx
Unit vii sorting
Data Structure and algorithms for software
Searching and sorting Techniques in Data structures
Sorting
358 33 powerpoint-slides_14-sorting_chapter-14
searching in data structure.pptx
Data Structure and Algorithm Chapter 2.ppsx Chapter 2.ppsx
UNIT V Searching Sorting Hashing Techniques [Autosaved].pptx
UNIT V Searching Sorting Hashing Techniques [Autosaved].pptx
Algorithm & data structures lec4&5
Insert Sort & Merge Sort Using C Programming
Sorting algorithms
Ad

Recently uploaded (20)

PDF
Lecture1 pattern recognition............
PDF
Introduction to Data Science and Data Analysis
PDF
Fluorescence-microscope_Botany_detailed content
PPTX
Supervised vs unsupervised machine learning algorithms
PPT
Miokarditis (Inflamasi pada Otot Jantung)
PPTX
ALIMENTARY AND BILIARY CONDITIONS 3-1.pptx
PPTX
AI Strategy room jwfjksfksfjsjsjsjsjfsjfsj
PPTX
Introduction to Firewall Analytics - Interfirewall and Transfirewall.pptx
PPTX
Database Infoormation System (DBIS).pptx
PPTX
Introduction to Knowledge Engineering Part 1
PDF
168300704-gasification-ppt.pdfhghhhsjsjhsuxush
PPTX
STERILIZATION AND DISINFECTION-1.ppthhhbx
PPTX
Business Ppt On Nestle.pptx huunnnhhgfvu
PPTX
mbdjdhjjodule 5-1 rhfhhfjtjjhafbrhfnfbbfnb
PPTX
01_intro xxxxxxxxxxfffffffffffaaaaaaaaaaafg
PDF
BF and FI - Blockchain, fintech and Financial Innovation Lesson 2.pdf
PDF
Introduction to the R Programming Language
PPTX
Market Analysis -202507- Wind-Solar+Hybrid+Street+Lights+for+the+North+Amer...
PDF
[EN] Industrial Machine Downtime Prediction
PPTX
MODULE 8 - DISASTER risk PREPAREDNESS.pptx
Lecture1 pattern recognition............
Introduction to Data Science and Data Analysis
Fluorescence-microscope_Botany_detailed content
Supervised vs unsupervised machine learning algorithms
Miokarditis (Inflamasi pada Otot Jantung)
ALIMENTARY AND BILIARY CONDITIONS 3-1.pptx
AI Strategy room jwfjksfksfjsjsjsjsjfsjfsj
Introduction to Firewall Analytics - Interfirewall and Transfirewall.pptx
Database Infoormation System (DBIS).pptx
Introduction to Knowledge Engineering Part 1
168300704-gasification-ppt.pdfhghhhsjsjhsuxush
STERILIZATION AND DISINFECTION-1.ppthhhbx
Business Ppt On Nestle.pptx huunnnhhgfvu
mbdjdhjjodule 5-1 rhfhhfjtjjhafbrhfnfbbfnb
01_intro xxxxxxxxxxfffffffffffaaaaaaaaaaafg
BF and FI - Blockchain, fintech and Financial Innovation Lesson 2.pdf
Introduction to the R Programming Language
Market Analysis -202507- Wind-Solar+Hybrid+Street+Lights+for+the+North+Amer...
[EN] Industrial Machine Downtime Prediction
MODULE 8 - DISASTER risk PREPAREDNESS.pptx
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