-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSearches.cpp
More file actions
61 lines (51 loc) · 1.37 KB
/
Copy pathSearches.cpp
File metadata and controls
61 lines (51 loc) · 1.37 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/*
* File: Searches.cpp
* Author: Josh
*
* Created on January 16, 2018, 5:07 PM
*/
#include "Searches.h"
//LINEAR::
//=============================================================================
int linearSearch(int array[], int size, int item){ //O(n)
//LINEAR SEARCH::
int index = -1;
bool found = false;
int i = 0;
while(!found && i < size){
if(array[i] == item){
found = true;
index=i;
}else{
i++;
}
}
return index;
}
//BINARY::
//=============================================================================
//PRECONDITION:: array must be sorted before use
int binarySearch(int array[], int size, int item){//O(log n)
int first = 0,
last = size-1,
middle;
int index = 1;
bool found = false;
while(!found && first <= last){
middle = (first + last)/2;
if(array[middle] == item){
found = true;
index = middle;
}else if(array[middle] > item){
last = middle-1;
}else{
last = middle+1;
}
}
return index;
}