0% found this document useful (0 votes)
5 views

CSLTR Week10

Uploaded by

lechitoan0356
Copyright
© © All Rights Reserved
Available Formats
Download as PPSX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

CSLTR Week10

Uploaded by

lechitoan0356
Copyright
© © All Rights Reserved
Available Formats
Download as PPSX, PDF, TXT or read online on Scribd
You are on page 1/ 26

SEARCH PROBLEM

Fundamentals of programming – Cơ sở lập trình


ADVISOR: Trương Toàn Thịnh

1
CONTENTS
Introduction
Linear search
Binary search

2
INTRODUCTION
 This problem is very popular
 Inputs of the problem are the information
needed and output is optimized solution
satisfying constraint condition
 Two methods of searching are linear and binary
 Search problem includes:
◦ Search space/solution space
◦ Constraint condition
 Solution space may include:
◦ Explicit: only choose and check
◦ Implicit: must create to continue processing
3
INTRODUCTION
 The process of choosing solutions includes
following steps:
◦ Step 0: create candidate solution (if not)
◦ Step 1: check if candidate solution satisfies constrain
condition or not
◦ Step 2: Among the candidate solutions satisfying
constrain condition, there are some standards to
choose the best one
 Example: Find the even biggest number in array
a with n whole distinct numbers (n > 0)
◦ Search space: n elements
◦ Constraint condition: even number
4
LINEAR SEARCH
(IN 1D ARRAY)
Problem 1: Let a be an array of n integers.
Write a function finding a value of the biggest
element 1 int FindMaxValue(int a[], int n){
2 int res = a[0];
3 for(int i = 1; i < n; i++){
4 if(a[i] > res) res = a[i];
5 }
6 return res;
7 }

◦ Cost: Loop array a  O(n)


◦ Search space: n elements
◦ Standard: biggest 5
LINEAR SEARCH
(IN 1D ARRAY)
 Problem 2: Let a be an array of n integers and number x.
Write a function finding the first position of appearance of x

1 int Find(int a[], int n, int x){ int Find(int a[], int n, int x){
2 int i = 0; int i = 0;
3 while((i < n) && (a[i] != x)) a[n] = x;
4 i++; while(a[i] != x) i++;
5 if(i < n) return i; if(i < n) return i;
6 return -1; return -1;
7 } }
◦ Cost: the luckiest is loop 1 time-looping. The average is n/2-
looping and the worst is n-looping  O(n)
◦ Search space: {0, n – 1}
◦ Constrain condition: value equal to x
◦ Standard: the element with the smallest index 6
LINEAR SEARCH
(IN 1D ARRAY)
 Problem 3: Let a be an array of n integers. Write a
function finding the position of the smallest square
number
1 bool iSquare(int number){ 8 if(iSquare(a[i]) && (idx==-1 || a[i]<lc){
2 int i = (int)sqrt((float)number); 9 lc = a[i];
3 return (i*i == number); 10 idx = i;
4 } 11 }
5 int IdxOfMinSquareNumber(int a[], int n){ 12 }
6 int idx = -1, lc = 0; 13 return idx;
7 for(int i = 0; i < n; i++){ 14 }

◦ Cost: loop n elements  O(n)


◦ Search space: {0, n – 1}
◦ Constrain condition: square number 7
LINEAR SEARCH
(IN 1D ARRAY)
 Problem 4: Let a be an array of n positive integers. Write
a function finding the position of the biggest prime
number
1 bool iSPrime(int number){ 8 int idxOfMaxPrime(int a[], int n){
2 if(number < 2) return false; 9 int idx = -1, lc = 0;
3 int n = (int)sqrt(number); 10 for(int i = 0; i < n; i++){
4 for(int i = 2; i <= n; i++) 11 if(iSPrime(a[i]) && a[i] > lc){
5 if(number % i == 0) return false; 12 lc = a[i]; idx = i;
6 return true; 13 }
7 } 14 }return idx;}

◦ Cost: loop n elements  O(n)


◦ Search space: {0, n – 1}
◦ Constrain condition: prime number 8
LINEAR SEARCH
(IN 1D STRUCTURAL ARRAY)
 Problem 5: Let sp be an array of n products. Each
product has: Code, product name and price. Write
a function finding the highest price in the list
1 #define MAX 100 8 float findMaxPrice(PRODUCT sp[], int n){
2 struct PRODUCT 9 float maxPrice = 0;
3 { 10 for(int i = 0; i < n; i++)
4 int id; 11 if(maxPrice < sp[i].Price)
5 char name[MAX + 1]; 12 maxPrice = sp[i].Price;
6 float price; 13 return maxPrice;
7 }; 14 }

◦ Cost: loop n elements  O(n)


◦ Search space: {0, n – 1}
◦ Standard: the highest price 9
LINEAR SEARCH
(IN 1D STRUCTURAL ARRAY)
 Problem 6: Let sp be an array of n products. Each product has:
Code, product name and price. Write a function finding the
product name with lowest price in the list
1 float findProduct(PRODUCT sp[], int n, char* strQuery, char* strProductName){
2 strcpy(strProductName, “”);
3 int idx = -1; float minP = 0;
4 for(int i = 0; i < n; i++)
5 if(strstr(sp[i].Name, strQuery) != NULL && (idx == -1 || minP > sp[i].Price)){
6 idx = i; minP = sp[i].Price;
7 }
8 if(idx != -1) strcpy(strProductName, sp[idx].Name);
9 }

◦ Cost: loop n elements  O(n)


◦ Search space: {0, n – 1}
10
◦ Constrain condition: exist product name needed
LINEAR SEARCH
(IN STRUCTURAL VECTOR)
 Problem 7: Let plist be an array of n songs. Each song includes: name,
singer, genre and points. Write a function choosing the songs with the
highest point
1 struct SONG 8 vector<SONG> FindBestSong(vectot<SONG>& pList){
2 { 9 vector<SONG> res; float bestR = 0;
3 string name; 10 for(int i = 0; i < pList.size(); i++)
4 string Artist; 11 if(bestR < pList[i].Rating)
5 string Genre; 12 bestR = pList[i].Rating;
6 float Rating; 13 for(i = 0; i < pList.size(); i++)
7 }; 14 if(bestR == pList[i].Rating)
Note: string in struct 15 res.push_back(pList[i]);
Following declarations are valid
SONG s; 16 return res;
Or
SONG* s = new SONG(); 17 }

◦ Cost: loop n elements  O(n)


◦ Search space: {0, n – 1} 11
LINEAR SEARCH
(IN LINKED LIST)
 Problem 8: Let a linked list of products. Each product
includes: code, name and price. Write a function finding
the highest price in the linked list
1 struct PRODUCT 8 float findMaxPrice(PRODUCT* sp){
2 { 9 PRODUCT* p = sp; float maxPrice = 0;
3 int id; 10 while(p){
4 char name[4]; 11 if(maxPrice < sp->price)
5 float price; 12 maxPrice = sp->price;
6 PRODUCT* next; 13 p = p->next;
7 }; 14 }
15 return maxPrice;
16 }

◦ Cost: loop n elements  O(n)


◦ Search space: {0, n – 1} 12
LINEAR SEARCH
(IN LINKED LIST)
Problem 8: review the structure PRODUCT
1 struct PRODUCT 8 void main()
2 { 9 {
3 int id; 10 PRODUCT* h = new PRODUCT;
4 char name[4]; 11 h->next = new PRODUCT;
5 float price; 12 h->next->next = NULL;
6 PRODUCT* next; 13 //cout<<…
7 }; 14 };

<???> <???>
2750f3c 2750f54
name name
<61ff1c> <2750f3c> <2750f54>
2750f38 2750f50 null
h id price next id price next
<2750f38> <2750f40> <2750f44> <2750f50> <2750f58>
13
LINEAR SEARCH
(IN LINKED LIST)
 Problem 9: Let a linked list of students. Each student includes: code,
name, faculty and GPA. Write a function counting a number of
students with GPA in [min, max]
1 #define DEPT 50 10 float count(STUDENT* s, char* strDept, float min, float max){
2 #define NAME 100 11 STUDENT* t = s; int c = 0;
3 struct STUDENT{ 12 while(t){
4 int ID; 13 if(strcmp(t->strDept, strDept) ==0 )
5 char strDept[DEPT+1]; 14 if(t->GPA>=min && t->GPA<=max) c++;
6 char strName[NAME+1]; 15 t = t->next;
7 float GPA; 16 }
8 STUDENT* next; 17 return c;
9 }; 18 }

◦ Cost: loop n elements  O(n)


◦ Constrain condition: exist the faculty name needed
◦ Search space: {0, n – 1} 14
LINEAR SEARCH
(IN HIERARCHICAL STRUCTURE)
 Problem 10: Counting a number of files with the size bigger
or equal to minSize in the given directory
1 struct File{ 10 int count(const Folder& f, int minSize){
2 string Name; 11 int i, c = 0, nFiles = f.Files.size(), nFolders = f.Folders.size();
3 int Size; 12 for(i = 0; i < nFiles; i++)
4 } 13 if(f.Files[i].Size >= minSize)
5 struct Folder{ 14 c++;
6 string Name; 15 for(i = 0; i < nFolders; i++)
7 vector<Folder> Folders; 16 c+=count(f.Folders[i], minSize);
8 vector<File> Files; 17 return c;
9 }; 18 }

◦ Cost: loop n files  O(n)


◦ Search space: multi-branch tree 15
LINEAR SEARCH
(IN HIERARCHICAL STRUCTURE)
 Problem 11: Search all the files with the name
contaning a given string strPat. Result is a list of
names (including file paths) of the files just found
◦ Cost: loop n files  O(n)
◦ Search space: multi-branch tree
◦ Standard: file with the name needed
Main(){ find(…,“HocTap”, “docx”,…);} Học tập
curPath = “HocTap”

NMLT KTLT Readme.docx TKB.png


currPath = “HocTap\\NMLT” currPath = “HocTap\\KTLT”

Bai1.docx

res = [“HocTap\\Readme.docx”,] “HocTap\\NMLT\\Bai1.docx”] 16


LINEAR SEARCH
(IN HIERARCHICAL STRUCTURE)
 Problem 11: Search all the files with the name contaning a given
string strPat. Result is a list of names (including file paths) of the
files just found
1 void find(const Folder& f, string strCurrentPath, string strPat, vector<string>& res){
2 int i, nFiles = f.Files.size(), nFolders = f.Folders.size();
3 string strFilePathName, strNewPath;
4 for(i = 0; i < nFiles; i++)
5 if(f.Files[i].Name.find(strPat, 0) != string::npos){
6 strFilePathName = strCurrentPath + “\\” + f.Files[i].Name;
7 res.push_back(strFilePathName);
8 }
9 for(i = 0; i < nFolders; i++)
10 find(f.Folders[i], strCurrentPath + “\\” + f.Folders[i].Name, strPat, res);
11 }

◦ Cost: loop n files  O(n)


◦ Search space: multi-branch tree 17
BINARY SEARCH
(IN 1D ARRAY)
 Problem 12: Let a be an array of n increasing
integers. Write a function determining the
position of the element having x value.
◦ If x > a[i]  x in [i + 1, n – 1]
◦ If x < a[i]  x in [0, i – 1]
1 void BinarySearch(int a[], int x, int n){
2 int from = 0, to = n – 1, mid;
3 while(from <= to){
4 mid = (from + to)/2;
0 1 2 3 4 5 6 7 8
5 if(a[mid] == x) return mid;
1 3 5 10 15 21 24 95 99
6 else{
7 if(a[mid] > x) to = mid – 1;
8 else from = mid + 1;
9 }} return -1;}
18
BINARY SEARCH
(IN 1D ARRAY)
Problem 13: Let a be an array of n
decreasing positive integers. Write a function
determining the position of the biggest
element smaller than x (for example x = 20)
1 int findMaxValue(int a[], int x, int n){
2 if(n == 0) return 0;
3 int from = 0, to = n – 1, mid;
4 while(from < to){
5 mid = (from + to)/2; 0 1 2 3 4 5 6 7
6 if(a[mid] > x) from = mid + 1;
80 55 46 24 21 15 10 9
7 else to = mid;
8 } > 20 > 20 < 20
9 if(a[from] <= x) return a[from];
10 return 0;
11 }
19
BINARY SEARCH
(IN 1D ARRAY)
 Problem 14: Let a be an array of n increasing
integers. Write a function inserting x into array,
such that maintaining the increasing order
1 void BinaryInsert(vector<int>& a, int x){
2 int from = 0, to = a.size() – 1, mid;
from = 02534 to = 413 mid = 413
2
3 while(from <= to){
4 mid = (from + to)/2; 0 1 2 3 4 5
5 if(a[mid] < x) from = mid + 1; 1 3 5 11
5 11 99

6 else to = mid – 1;
7 }
x = 99
5
8 a.insert(a.begin + from, x);
9 }

20
BINARY SEARCH
(IN 1D ARRAY)
Problem 15: Let a be an unimodal array
with n integer elements. Write a function
finding the biggest element
1 int BinarySearchMax(int a[], int n){
2 int from = 0, to = n – 1, mid;
from = 203 to = 36 mid = 32
1
3 while(from < to){
4 mid = (from + to)/2; 0 1 2 3 4 5 6
5 if(a[mid] < a[mid + 1]) from = mid + 1; 1 4 8 9 7 6 2

6 else to = mid;
7 }
8 return a[from];
9 }

21
BINARY SEARCH
(IN 1D STRUCTURAL ARRAY)
 Problem 16: Any library has the books with the names following the alphabetically increasing order.
Write a function determining the position of the book needed

1 struct POSITION{ 10 POSITION BinarySearch (vector<BOOK> &Lst, string strTitle){


2 int BookShelf, Level; 11 POSITION res; res.BookShelf = res.Level = -1; int n = Lst.size();
3 }; 12 if(n == 0) return res;
4 struct BOOK{ 13 int from = 0, to = n – 1, mid;
5 string Title; 14 while(from <= to){
6 string Authors; 15 mid = (from + to)/2;
7 string Publisher; 16 if(Lst[mid].Title == strTitle) return Lst[mid].Position;
8 POSITION Position; 17 else{
9 }; 18 if(Lst[mid].Title > strTitle) to = mid – 1;
19 else from = mid + 1;
20 }
21 } return res;
22 } 22
BINARY SEARCH
(IN 1D STRUCTURAL ARRAY)
 Problem 17: write a function determining the camera’s name with the
highest price not exceeding maxPrice. The camera’s information
includes name, manufacturer and price
1 struct CAMERA{ 6 void findCam(CAMERA lst[], int n, float maxPrice, char* strName){
2 char ProductName[50]; 7 strcpy(strName, “”);
3 char Manufacturer[50]; 8 if(n == 0) return;
4 float Price; 9 int from = 0, to = n – 1, mid;
5 }; 10 while(from < to){
11 mid = (from + to)/2;
12 if(lst[mid].Price > maxPrice) to = mid – 1;
13 else from = mid;
14 }
15 if(lst[from].Price<=maxPrice)strcpy(strName, lst[from].ProductName);
16 }
23
BINARY SEARCH
(IN 1D STRUCTURAL ARRAY)
 Problem 18: Write a function adding a record into the contact, such
that all records follow the rule of Name alphabetically increasing

1 struct CONTACT{ 6 void binaryInsert(vector<CONTACT>& lst, CONTACT newContact){


2 string Name; 7 int from = 0, to = lst.size() – 1, mid;
3 string PhoneNumber; 8 while(from <= to){
4 string EmailAddress; 9 mid = (from + to)/2;
5 }; 10 if(lst[mid].Name < newContact.Name) from = mid + 1;
11 else to = mid – 1;
12 }
13 lst.insert(lst.begin() + from, newContact);
14 }

24
BINARY SEARCH
(IN 2D ARRAY)
 Problem 19: Let a be integer array (m  n). Array a has the numbers left-to-
right increasing in each row. Write a function checking if array a contains the
element with x value or not (for example x = 14).
1 bool search2D(int** a, int m, int n, int x){
2 int from, to, mid;
3 for(int i = 0; i < m; i++){
4 from = 0; to = n – 1; 4 7 9 21  loop log24
5 while(from <= to){ 7 9 11 43  loop log24
6 mid = (from + to)/2; 8 9 44 67  loop log24
 loop log24 6log24
7 if(a[i][mid] == x) return true; 1 3 4 6
8 else{ 2 4 6 7  loop log24
9 if(a[i][mid] < x) from = mid + 1; 1 1 6 7  loop log24
10 else to = mid – 1;
11 }}}
12 return false; } 25
BINARY SEARCH
(IN 2D ARRAY)
 Problem 20: Let a be integer array (m  n). Array a has the
numbers left-to-right increasing in each row, and numbers
bottom-to-up increasing in each column. Write a function
checking if array a contains the element with x value or not (for
example x = 14)
1 bool search2D(int** a, int m, int n, int x){ j
2 int i = 0, j = 0; 
0 1 2 3 4
3 while(i < m && j < n){
i 0 7 12 16 20 95
4 if(a[i][j] == x) return true;
1 5 9 14 15 19
5 else{
2 3 5 7 9 11
6 if(a[i][j] < x) j++;
3 1 2 3 4 5
7 else i++;
8 }
Loop cost O(m + n)
9 return false;
10 } 26

You might also like