SlideShare a Scribd company logo
1 of 27
Download to read offline
Chapter Two
Time complexity of known algorithms
•Searching
Linear Search
Binary Search
•Sorting
Insertion Sort
Selection Sort
Bubble Sort
1/12/2023 1
Searching: Linear Search
Linear search is a very simple search algorithm. In this type of search, a sequential search is
made over all items one by one. Every item is checked and if a match is found then that
particular item is returned, otherwise the search continues till the end of the data
collection.
Algorithm: Linear Search (Array A, Value x)
• Step 1: Set i to 1
• Step 2: if i > n then go to step 7
• Step 3: if A[i] = x then go to step 6
• Step 4: Set i to i + 1
• Step 5: Go to Step 2
• Step 6: Print Element x Found at index i and go to step 8
• Step 7: Print element not found
• Step 8: Exit
1/12/2023 2
The implementation of the algorithm:
#include<stdio.h>
#include<stdlib.h>
#include<conio.h>
int main(){
int
array[50],i,target,num;
printf("How many elements
do you want in the array");
scanf("%d",&num);
printf("Enter array
elements:");
for(i=0;i<num;++i)
scanf("%d",&array[i]);
printf("Enter element to search:");
scanf("%d",&target);
for(i=0;i<num;++i)
if(array[i]==target)
break;
if(i<num)
printf("Target element found at location %d",i);
else
printf("Target element not found in an array");
return 0;
}
1/12/2023 3
Binary Search
• Binary search is a fast search algorithm with run-time complexity of Ο(log n).
• This search algorithm works on the principle of divide and conquer.
• For this algorithm to work properly, the data collection should be in the sorted form.
• Binary search looks for a particular item by comparing the middle most item of the
collection.
• If a match occurs, then the index of item is returned.
• If the middle item is greater than the item, then the item is searched in the sub-array to
the left of the middle item.
• Otherwise, the item is searched for in the sub-array to the right of the middle item.
• This process continues on the sub-array as well until the size of the subarray reduces to
zero.
1/12/2023 4
1/12/2023 5
1/12/2023 6
…cont
1/12/2023 7
Pseudocode
Procedure binary_search:
• A ← sorted array
• n ← size of array
• x ← value to be searched
• Set lowerBound = 1
• Set upperBound = n
• while x not found
• if upperBound < lowerBound
• EXIT: x does not exists.
• set midPoint = lowerBound + ( upperBound - lowerBound ) / 2
• if A[midPoint] < x
• set lowerBound = midPoint + 1
• if A[midPoint] > x
• set upperBound = midPoint - 1
• if A[midPoint] = x
• EXIT: x found at location midPoint
• end while
• end procedure
1/12/2023 8
Binary Search Algorithm Implimentation
#include <iostream>
using namespace std;
int binarySearch(int arr[], int left, int right, int x) {
while (left <= right) {
int mid = left + (right - left) / 2;
if (arr[mid] == x) {
return mid;
}
else if (arr[mid] < x) {
left = mid + 1;
}
else
{
right = mid - 1;
} }
return -1;
}
1/12/2023 9
int main() {
int myarr[10];
int num;
int output;
cout << "Please enter 10 elements ASCENDING order" << endl;
for (int i = 0; i < 10; i++) {
cin >> myarr[i];
}
cout << "Please enter an element to search" << endl;
cin >> num;
output = binarySearch(myarr, 0, 9, num);
if (output == -1) {
cout << "No Match Found" << endl;
} else {
cout << "Match found at position: " << output << endl;
}
return 0;
}
Sorting
Insertion Sort: Insertion sort is a sorting algorithm that places an unsorted element at its suitable
place in each iteration.
1. The first element in the array is assumed to be sorted. Take the second
element and store it separately in key.
Compare key with the first element. If the first element is greater than key,
then key is placed in front of the first element.
1/12/2023 10
 Suppose we need to sort the following array.
Initial array
… cont
1/12/2023 11
… cont
2. Now, the first two elements are sorted.
Take the third element and compare it with the elements on the left
of it. Placed it just behind the element smaller than it. If there is no
element smaller than it, then place it at the beginning of the array.
1/12/2023 12
… cont
3. Similarly, place every unsorted element at its correct position
1/12/2023 13
Algorithm …
1/12/2023 14
Implimentation
// Insertion sort in C++
#include <iostream>
using namespace std;
// Function to print an array
void printArray(int array[], int size) {
for (int i = 0; i < size; i++) {
cout << array[i] << " ";
}
cout << endl;
}
void insertionSort(int array[], int size) {
for (int step = 1; step < size; step++) {
int key = array[step];
int j = step - 1;
1/12/2023 15
// Compare key with each element on the left of
it until an element smaller than // it is found.
// For descending order, change key<array[j] to
key>array[j].
while (key < array[j] && j >= 0) {
array[j + 1] = array[j]; --j;
}
array[j + 1] = key;
} }
// Driver code
int main() {
int data[] = {9, 5, 1, 4, 3};
int size = sizeof(data) / sizeof(data[0]);
insertionSort(data, size);
cout << "Sorted array in ascending order:n";
printArray(data, size);
}
Selection Sort
• Selection sort is a sorting algorithm that selects the smallest element
from an unsorted list in each iteration and places that element at the
beginning of the unsorted list.
1. Select first element as minimum
2. Compare minimum with the second element. If the second element is
smaller than minimum, assign the second element as minimum.
Compare minimum with the third element. Again, if the third element is
smaller, then assign minimum to the third element otherwise do nothing. The
process goes on until the last element.
1/12/2023 16
… cont
• Compare minimum with the remaining elements
1/12/2023 17
… cont
1/12/2023 18
… cont
1/12/2023 19
Selection Sort
1/12/2023 20
Selection Sort Implimentation
// To sort in descending order, change > to <
in this line. // Select the minimum element in
each loop.
if (array[i] < array[min_idx]) min_idx = i;
}
// put min at the correct position
swap(&array[min_idx], &array[step]);
} }
// driver code
int main() {
int data[] = {20, 12, 10, 15, 2};
int size = sizeof(data) / sizeof(data[0]);
selectionSort(data, size);
cout << "Sorted array in Acsending
Order:n";
printArray(data, size);
}
1/12/2023 21
// Selection sort in C++
#include <iostream>
using namespace std;
// function to swap the the position of two elements
void swap(int *a, int *b) {
int temp = *a; *a = *b; *b = temp;
}
// function to print an array
void printArray(int array[], int size) {
for (int i = 0; i < size; i++) {
cout << array[i] << " ";
}
cout << endl;
}
void selectionSort(int array[], int size) {
for (int step = 0;
step < size - 1; step++) {
int min_idx = step;
for (int i = step + 1; i < size; i++) {
Bubble Sort
• Bubble sort is a sorting algorithm that compares two adjacent elements
and swaps them until they are in the intended order.
• Suppose we are trying to sort the elements in ascending order.
First Iteration (Compare and Swap)
1. Starting from the first index, compare the first and the second elements.
2. If the first element is greater than the second element, they are
swapped.
3. Now, compare the second and the third elements. Swap them if they are
not in order.
4. The above process goes on until the last element.
1/12/2023 22
… cont
1/12/2023 23
2. Remaining Iteration
The same process goes on for the remaining iterations.
After each iteration, the largest element among the
unsorted elements is placed at the end.
Put the largest element at the end
… cont
• In each iteration, the comparison takes place up to the last unsorted
element.
• Compare the adjacent elements
• The array is sorted when all the
unsorted elements are placed at
their correct positions.
1/12/2023 24
The array is sorted if all elements
are kept in the right order
… cont
1/12/2023 25
Bubble Sort Implementation
// Bubble sort in C++
#include <iostream>
using namespace std;
// perform bubble sort
void bubbleSort(int array[], int size) {
// loop to access each array element
for (int step = 0; step < size; ++step) {
// loop to compare array elements
for (int i = 0; i < size - step; ++i) {
// compare two adjacent elements // change
> to < to sort in descending order
if (array[i] > array[i + 1]) {
// swapping elements if elements // are not
in the intended order
int temp = array[i];
array[i] = array[i + 1]; array[i + 1] = temp;
} } } }
// print array
void printArray(int array[], int size) {
for (int i = 0; i < size; ++i) {
cout << " " << array[i];
}
cout << "n"; } int main() {
int data[] = {-2, 45, 0, 11, -9};
// find array's length
int size = sizeof(data) / sizeof(data[0]);
bubbleSort(data, size);
cout << "Sorted Array in Ascending
Order:n";
printArray(data, size);
}
1/12/2023 26
Thank You!
?
1/12/2023 27

More Related Content

Similar to Chapter Two.pdf

Data structures arrays
Data structures   arraysData structures   arrays
Data structures arraysmaamir farooq
 
advanced searching and sorting.pdf
advanced searching and sorting.pdfadvanced searching and sorting.pdf
advanced searching and sorting.pdfharamaya university
 
Data structure using c module 3
Data structure using c module 3Data structure using c module 3
Data structure using c module 3smruti sarangi
 
Searching and sorting Techniques in Data structures
Searching and sorting Techniques in Data structuresSearching and sorting Techniques in Data structures
Searching and sorting Techniques in Data structuresPRIANKA R
 
Selection sort
Selection sortSelection sort
Selection sortasra khan
 
Required to augment the authors Binary Search Tree (BST) code to .docx
Required to augment the authors Binary Search Tree (BST) code to .docxRequired to augment the authors Binary Search Tree (BST) code to .docx
Required to augment the authors Binary Search Tree (BST) code to .docxdebishakespeare
 
Updated Lab3.docx
Updated Lab3.docxUpdated Lab3.docx
Updated Lab3.docxAleezaAnjum
 
Advanced s and s algorithm.ppt
Advanced s and s algorithm.pptAdvanced s and s algorithm.ppt
Advanced s and s algorithm.pptLegesseSamuel
 
linear search and binary search
linear search and binary searchlinear search and binary search
linear search and binary searchZia Ush Shamszaman
 
SORTING techniques.pptx
SORTING techniques.pptxSORTING techniques.pptx
SORTING techniques.pptxDr.Shweta
 
CP PPT_Unit IV computer programming in c.pdf
CP PPT_Unit IV computer programming in c.pdfCP PPT_Unit IV computer programming in c.pdf
CP PPT_Unit IV computer programming in c.pdfsaneshgamerz
 
In the binary search, if the array being searched has 32 elements in.pdf
In the binary search, if the array being searched has 32 elements in.pdfIn the binary search, if the array being searched has 32 elements in.pdf
In the binary search, if the array being searched has 32 elements in.pdfarpitaeron555
 

Similar to Chapter Two.pdf (20)

Data structures arrays
Data structures   arraysData structures   arrays
Data structures arrays
 
9 Arrays
9 Arrays9 Arrays
9 Arrays
 
advanced searching and sorting.pdf
advanced searching and sorting.pdfadvanced searching and sorting.pdf
advanced searching and sorting.pdf
 
Algo PPT.pdf
Algo PPT.pdfAlgo PPT.pdf
Algo PPT.pdf
 
Data structure using c module 3
Data structure using c module 3Data structure using c module 3
Data structure using c module 3
 
Searching and sorting Techniques in Data structures
Searching and sorting Techniques in Data structuresSearching and sorting Techniques in Data structures
Searching and sorting Techniques in Data structures
 
Selection sort
Selection sortSelection sort
Selection sort
 
Heap, quick and merge sort
Heap, quick and merge sortHeap, quick and merge sort
Heap, quick and merge sort
 
Required to augment the authors Binary Search Tree (BST) code to .docx
Required to augment the authors Binary Search Tree (BST) code to .docxRequired to augment the authors Binary Search Tree (BST) code to .docx
Required to augment the authors Binary Search Tree (BST) code to .docx
 
Data Structures 7
Data Structures 7Data Structures 7
Data Structures 7
 
Updated Lab3.docx
Updated Lab3.docxUpdated Lab3.docx
Updated Lab3.docx
 
Sorting
SortingSorting
Sorting
 
Advanced s and s algorithm.ppt
Advanced s and s algorithm.pptAdvanced s and s algorithm.ppt
Advanced s and s algorithm.ppt
 
linear search and binary search
linear search and binary searchlinear search and binary search
linear search and binary search
 
Chapter3.pptx
Chapter3.pptxChapter3.pptx
Chapter3.pptx
 
SORTING techniques.pptx
SORTING techniques.pptxSORTING techniques.pptx
SORTING techniques.pptx
 
search_sort.ppt
search_sort.pptsearch_sort.ppt
search_sort.ppt
 
CP PPT_Unit IV computer programming in c.pdf
CP PPT_Unit IV computer programming in c.pdfCP PPT_Unit IV computer programming in c.pdf
CP PPT_Unit IV computer programming in c.pdf
 
In the binary search, if the array being searched has 32 elements in.pdf
In the binary search, if the array being searched has 32 elements in.pdfIn the binary search, if the array being searched has 32 elements in.pdf
In the binary search, if the array being searched has 32 elements in.pdf
 
UNIT V.docx
UNIT V.docxUNIT V.docx
UNIT V.docx
 

Recently uploaded

Computer Networks Basics of Network Devices
Computer Networks  Basics of Network DevicesComputer Networks  Basics of Network Devices
Computer Networks Basics of Network DevicesChandrakantDivate1
 
Linux Systems Programming: Inter Process Communication (IPC) using Pipes
Linux Systems Programming: Inter Process Communication (IPC) using PipesLinux Systems Programming: Inter Process Communication (IPC) using Pipes
Linux Systems Programming: Inter Process Communication (IPC) using PipesRashidFaridChishti
 
Post office management system project ..pdf
Post office management system project ..pdfPost office management system project ..pdf
Post office management system project ..pdfKamal Acharya
 
Introduction to Data Visualization,Matplotlib.pdf
Introduction to Data Visualization,Matplotlib.pdfIntroduction to Data Visualization,Matplotlib.pdf
Introduction to Data Visualization,Matplotlib.pdfsumitt6_25730773
 
1_Introduction + EAM Vocabulary + how to navigate in EAM.pdf
1_Introduction + EAM Vocabulary + how to navigate in EAM.pdf1_Introduction + EAM Vocabulary + how to navigate in EAM.pdf
1_Introduction + EAM Vocabulary + how to navigate in EAM.pdfAldoGarca30
 
Introduction to Robotics in Mechanical Engineering.pptx
Introduction to Robotics in Mechanical Engineering.pptxIntroduction to Robotics in Mechanical Engineering.pptx
Introduction to Robotics in Mechanical Engineering.pptxhublikarsn
 
Theory of Time 2024 (Universal Theory for Everything)
Theory of Time 2024 (Universal Theory for Everything)Theory of Time 2024 (Universal Theory for Everything)
Theory of Time 2024 (Universal Theory for Everything)Ramkumar k
 
AIRCANVAS[1].pdf mini project for btech students
AIRCANVAS[1].pdf mini project for btech studentsAIRCANVAS[1].pdf mini project for btech students
AIRCANVAS[1].pdf mini project for btech studentsvanyagupta248
 
COST-EFFETIVE and Energy Efficient BUILDINGS ptx
COST-EFFETIVE  and Energy Efficient BUILDINGS ptxCOST-EFFETIVE  and Energy Efficient BUILDINGS ptx
COST-EFFETIVE and Energy Efficient BUILDINGS ptxJIT KUMAR GUPTA
 
HAND TOOLS USED AT ELECTRONICS WORK PRESENTED BY KOUSTAV SARKAR
HAND TOOLS USED AT ELECTRONICS WORK PRESENTED BY KOUSTAV SARKARHAND TOOLS USED AT ELECTRONICS WORK PRESENTED BY KOUSTAV SARKAR
HAND TOOLS USED AT ELECTRONICS WORK PRESENTED BY KOUSTAV SARKARKOUSTAV SARKAR
 
8th International Conference on Soft Computing, Mathematics and Control (SMC ...
8th International Conference on Soft Computing, Mathematics and Control (SMC ...8th International Conference on Soft Computing, Mathematics and Control (SMC ...
8th International Conference on Soft Computing, Mathematics and Control (SMC ...josephjonse
 
Query optimization and processing for advanced database systems
Query optimization and processing for advanced database systemsQuery optimization and processing for advanced database systems
Query optimization and processing for advanced database systemsmeharikiros2
 
Kuwait City MTP kit ((+919101817206)) Buy Abortion Pills Kuwait
Kuwait City MTP kit ((+919101817206)) Buy Abortion Pills KuwaitKuwait City MTP kit ((+919101817206)) Buy Abortion Pills Kuwait
Kuwait City MTP kit ((+919101817206)) Buy Abortion Pills Kuwaitjaanualu31
 
"Lesotho Leaps Forward: A Chronicle of Transformative Developments"
"Lesotho Leaps Forward: A Chronicle of Transformative Developments""Lesotho Leaps Forward: A Chronicle of Transformative Developments"
"Lesotho Leaps Forward: A Chronicle of Transformative Developments"mphochane1998
 
8086 Microprocessor Architecture: 16-bit microprocessor
8086 Microprocessor Architecture: 16-bit microprocessor8086 Microprocessor Architecture: 16-bit microprocessor
8086 Microprocessor Architecture: 16-bit microprocessorAshwiniTodkar4
 
Standard vs Custom Battery Packs - Decoding the Power Play
Standard vs Custom Battery Packs - Decoding the Power PlayStandard vs Custom Battery Packs - Decoding the Power Play
Standard vs Custom Battery Packs - Decoding the Power PlayEpec Engineered Technologies
 
PE 459 LECTURE 2- natural gas basic concepts and properties
PE 459 LECTURE 2- natural gas basic concepts and propertiesPE 459 LECTURE 2- natural gas basic concepts and properties
PE 459 LECTURE 2- natural gas basic concepts and propertiessarkmank1
 
Hospital management system project report.pdf
Hospital management system project report.pdfHospital management system project report.pdf
Hospital management system project report.pdfKamal Acharya
 
Electromagnetic relays used for power system .pptx
Electromagnetic relays used for power system .pptxElectromagnetic relays used for power system .pptx
Electromagnetic relays used for power system .pptxNANDHAKUMARA10
 

Recently uploaded (20)

Integrated Test Rig For HTFE-25 - Neometrix
Integrated Test Rig For HTFE-25 - NeometrixIntegrated Test Rig For HTFE-25 - Neometrix
Integrated Test Rig For HTFE-25 - Neometrix
 
Computer Networks Basics of Network Devices
Computer Networks  Basics of Network DevicesComputer Networks  Basics of Network Devices
Computer Networks Basics of Network Devices
 
Linux Systems Programming: Inter Process Communication (IPC) using Pipes
Linux Systems Programming: Inter Process Communication (IPC) using PipesLinux Systems Programming: Inter Process Communication (IPC) using Pipes
Linux Systems Programming: Inter Process Communication (IPC) using Pipes
 
Post office management system project ..pdf
Post office management system project ..pdfPost office management system project ..pdf
Post office management system project ..pdf
 
Introduction to Data Visualization,Matplotlib.pdf
Introduction to Data Visualization,Matplotlib.pdfIntroduction to Data Visualization,Matplotlib.pdf
Introduction to Data Visualization,Matplotlib.pdf
 
1_Introduction + EAM Vocabulary + how to navigate in EAM.pdf
1_Introduction + EAM Vocabulary + how to navigate in EAM.pdf1_Introduction + EAM Vocabulary + how to navigate in EAM.pdf
1_Introduction + EAM Vocabulary + how to navigate in EAM.pdf
 
Introduction to Robotics in Mechanical Engineering.pptx
Introduction to Robotics in Mechanical Engineering.pptxIntroduction to Robotics in Mechanical Engineering.pptx
Introduction to Robotics in Mechanical Engineering.pptx
 
Theory of Time 2024 (Universal Theory for Everything)
Theory of Time 2024 (Universal Theory for Everything)Theory of Time 2024 (Universal Theory for Everything)
Theory of Time 2024 (Universal Theory for Everything)
 
AIRCANVAS[1].pdf mini project for btech students
AIRCANVAS[1].pdf mini project for btech studentsAIRCANVAS[1].pdf mini project for btech students
AIRCANVAS[1].pdf mini project for btech students
 
COST-EFFETIVE and Energy Efficient BUILDINGS ptx
COST-EFFETIVE  and Energy Efficient BUILDINGS ptxCOST-EFFETIVE  and Energy Efficient BUILDINGS ptx
COST-EFFETIVE and Energy Efficient BUILDINGS ptx
 
HAND TOOLS USED AT ELECTRONICS WORK PRESENTED BY KOUSTAV SARKAR
HAND TOOLS USED AT ELECTRONICS WORK PRESENTED BY KOUSTAV SARKARHAND TOOLS USED AT ELECTRONICS WORK PRESENTED BY KOUSTAV SARKAR
HAND TOOLS USED AT ELECTRONICS WORK PRESENTED BY KOUSTAV SARKAR
 
8th International Conference on Soft Computing, Mathematics and Control (SMC ...
8th International Conference on Soft Computing, Mathematics and Control (SMC ...8th International Conference on Soft Computing, Mathematics and Control (SMC ...
8th International Conference on Soft Computing, Mathematics and Control (SMC ...
 
Query optimization and processing for advanced database systems
Query optimization and processing for advanced database systemsQuery optimization and processing for advanced database systems
Query optimization and processing for advanced database systems
 
Kuwait City MTP kit ((+919101817206)) Buy Abortion Pills Kuwait
Kuwait City MTP kit ((+919101817206)) Buy Abortion Pills KuwaitKuwait City MTP kit ((+919101817206)) Buy Abortion Pills Kuwait
Kuwait City MTP kit ((+919101817206)) Buy Abortion Pills Kuwait
 
"Lesotho Leaps Forward: A Chronicle of Transformative Developments"
"Lesotho Leaps Forward: A Chronicle of Transformative Developments""Lesotho Leaps Forward: A Chronicle of Transformative Developments"
"Lesotho Leaps Forward: A Chronicle of Transformative Developments"
 
8086 Microprocessor Architecture: 16-bit microprocessor
8086 Microprocessor Architecture: 16-bit microprocessor8086 Microprocessor Architecture: 16-bit microprocessor
8086 Microprocessor Architecture: 16-bit microprocessor
 
Standard vs Custom Battery Packs - Decoding the Power Play
Standard vs Custom Battery Packs - Decoding the Power PlayStandard vs Custom Battery Packs - Decoding the Power Play
Standard vs Custom Battery Packs - Decoding the Power Play
 
PE 459 LECTURE 2- natural gas basic concepts and properties
PE 459 LECTURE 2- natural gas basic concepts and propertiesPE 459 LECTURE 2- natural gas basic concepts and properties
PE 459 LECTURE 2- natural gas basic concepts and properties
 
Hospital management system project report.pdf
Hospital management system project report.pdfHospital management system project report.pdf
Hospital management system project report.pdf
 
Electromagnetic relays used for power system .pptx
Electromagnetic relays used for power system .pptxElectromagnetic relays used for power system .pptx
Electromagnetic relays used for power system .pptx
 

Chapter Two.pdf

  • 1. Chapter Two Time complexity of known algorithms •Searching Linear Search Binary Search •Sorting Insertion Sort Selection Sort Bubble Sort 1/12/2023 1
  • 2. Searching: Linear Search Linear search is a very simple search algorithm. In this type of search, a sequential search is made over all items one by one. Every item is checked and if a match is found then that particular item is returned, otherwise the search continues till the end of the data collection. Algorithm: Linear Search (Array A, Value x) • Step 1: Set i to 1 • Step 2: if i > n then go to step 7 • Step 3: if A[i] = x then go to step 6 • Step 4: Set i to i + 1 • Step 5: Go to Step 2 • Step 6: Print Element x Found at index i and go to step 8 • Step 7: Print element not found • Step 8: Exit 1/12/2023 2
  • 3. The implementation of the algorithm: #include<stdio.h> #include<stdlib.h> #include<conio.h> int main(){ int array[50],i,target,num; printf("How many elements do you want in the array"); scanf("%d",&num); printf("Enter array elements:"); for(i=0;i<num;++i) scanf("%d",&array[i]); printf("Enter element to search:"); scanf("%d",&target); for(i=0;i<num;++i) if(array[i]==target) break; if(i<num) printf("Target element found at location %d",i); else printf("Target element not found in an array"); return 0; } 1/12/2023 3
  • 4. Binary Search • Binary search is a fast search algorithm with run-time complexity of Ο(log n). • This search algorithm works on the principle of divide and conquer. • For this algorithm to work properly, the data collection should be in the sorted form. • Binary search looks for a particular item by comparing the middle most item of the collection. • If a match occurs, then the index of item is returned. • If the middle item is greater than the item, then the item is searched in the sub-array to the left of the middle item. • Otherwise, the item is searched for in the sub-array to the right of the middle item. • This process continues on the sub-array as well until the size of the subarray reduces to zero. 1/12/2023 4
  • 8. Pseudocode Procedure binary_search: • A ← sorted array • n ← size of array • x ← value to be searched • Set lowerBound = 1 • Set upperBound = n • while x not found • if upperBound < lowerBound • EXIT: x does not exists. • set midPoint = lowerBound + ( upperBound - lowerBound ) / 2 • if A[midPoint] < x • set lowerBound = midPoint + 1 • if A[midPoint] > x • set upperBound = midPoint - 1 • if A[midPoint] = x • EXIT: x found at location midPoint • end while • end procedure 1/12/2023 8
  • 9. Binary Search Algorithm Implimentation #include <iostream> using namespace std; int binarySearch(int arr[], int left, int right, int x) { while (left <= right) { int mid = left + (right - left) / 2; if (arr[mid] == x) { return mid; } else if (arr[mid] < x) { left = mid + 1; } else { right = mid - 1; } } return -1; } 1/12/2023 9 int main() { int myarr[10]; int num; int output; cout << "Please enter 10 elements ASCENDING order" << endl; for (int i = 0; i < 10; i++) { cin >> myarr[i]; } cout << "Please enter an element to search" << endl; cin >> num; output = binarySearch(myarr, 0, 9, num); if (output == -1) { cout << "No Match Found" << endl; } else { cout << "Match found at position: " << output << endl; } return 0; }
  • 10. Sorting Insertion Sort: Insertion sort is a sorting algorithm that places an unsorted element at its suitable place in each iteration. 1. The first element in the array is assumed to be sorted. Take the second element and store it separately in key. Compare key with the first element. If the first element is greater than key, then key is placed in front of the first element. 1/12/2023 10  Suppose we need to sort the following array. Initial array
  • 12. … cont 2. Now, the first two elements are sorted. Take the third element and compare it with the elements on the left of it. Placed it just behind the element smaller than it. If there is no element smaller than it, then place it at the beginning of the array. 1/12/2023 12
  • 13. … cont 3. Similarly, place every unsorted element at its correct position 1/12/2023 13
  • 15. Implimentation // Insertion sort in C++ #include <iostream> using namespace std; // Function to print an array void printArray(int array[], int size) { for (int i = 0; i < size; i++) { cout << array[i] << " "; } cout << endl; } void insertionSort(int array[], int size) { for (int step = 1; step < size; step++) { int key = array[step]; int j = step - 1; 1/12/2023 15 // Compare key with each element on the left of it until an element smaller than // it is found. // For descending order, change key<array[j] to key>array[j]. while (key < array[j] && j >= 0) { array[j + 1] = array[j]; --j; } array[j + 1] = key; } } // Driver code int main() { int data[] = {9, 5, 1, 4, 3}; int size = sizeof(data) / sizeof(data[0]); insertionSort(data, size); cout << "Sorted array in ascending order:n"; printArray(data, size); }
  • 16. Selection Sort • Selection sort is a sorting algorithm that selects the smallest element from an unsorted list in each iteration and places that element at the beginning of the unsorted list. 1. Select first element as minimum 2. Compare minimum with the second element. If the second element is smaller than minimum, assign the second element as minimum. Compare minimum with the third element. Again, if the third element is smaller, then assign minimum to the third element otherwise do nothing. The process goes on until the last element. 1/12/2023 16
  • 17. … cont • Compare minimum with the remaining elements 1/12/2023 17
  • 21. Selection Sort Implimentation // To sort in descending order, change > to < in this line. // Select the minimum element in each loop. if (array[i] < array[min_idx]) min_idx = i; } // put min at the correct position swap(&array[min_idx], &array[step]); } } // driver code int main() { int data[] = {20, 12, 10, 15, 2}; int size = sizeof(data) / sizeof(data[0]); selectionSort(data, size); cout << "Sorted array in Acsending Order:n"; printArray(data, size); } 1/12/2023 21 // Selection sort in C++ #include <iostream> using namespace std; // function to swap the the position of two elements void swap(int *a, int *b) { int temp = *a; *a = *b; *b = temp; } // function to print an array void printArray(int array[], int size) { for (int i = 0; i < size; i++) { cout << array[i] << " "; } cout << endl; } void selectionSort(int array[], int size) { for (int step = 0; step < size - 1; step++) { int min_idx = step; for (int i = step + 1; i < size; i++) {
  • 22. Bubble Sort • Bubble sort is a sorting algorithm that compares two adjacent elements and swaps them until they are in the intended order. • Suppose we are trying to sort the elements in ascending order. First Iteration (Compare and Swap) 1. Starting from the first index, compare the first and the second elements. 2. If the first element is greater than the second element, they are swapped. 3. Now, compare the second and the third elements. Swap them if they are not in order. 4. The above process goes on until the last element. 1/12/2023 22
  • 23. … cont 1/12/2023 23 2. Remaining Iteration The same process goes on for the remaining iterations. After each iteration, the largest element among the unsorted elements is placed at the end. Put the largest element at the end
  • 24. … cont • In each iteration, the comparison takes place up to the last unsorted element. • Compare the adjacent elements • The array is sorted when all the unsorted elements are placed at their correct positions. 1/12/2023 24 The array is sorted if all elements are kept in the right order
  • 26. Bubble Sort Implementation // Bubble sort in C++ #include <iostream> using namespace std; // perform bubble sort void bubbleSort(int array[], int size) { // loop to access each array element for (int step = 0; step < size; ++step) { // loop to compare array elements for (int i = 0; i < size - step; ++i) { // compare two adjacent elements // change > to < to sort in descending order if (array[i] > array[i + 1]) { // swapping elements if elements // are not in the intended order int temp = array[i]; array[i] = array[i + 1]; array[i + 1] = temp; } } } } // print array void printArray(int array[], int size) { for (int i = 0; i < size; ++i) { cout << " " << array[i]; } cout << "n"; } int main() { int data[] = {-2, 45, 0, 11, -9}; // find array's length int size = sizeof(data) / sizeof(data[0]); bubbleSort(data, size); cout << "Sorted Array in Ascending Order:n"; printArray(data, size); } 1/12/2023 26