














































Prepara tus exámenes y mejora tus resultados gracias a la gran cantidad de recursos disponibles en Docsity
Gana puntos ayudando a otros estudiantes o consíguelos activando un Plan Premium
Esta página no es visible en la vista previa
¡No te pierdas las partes importantes!















































P R O G R A M M I N G Y E A R 2 0 2 0 - 2 0 2 1
LINEAR SEARCH ALGORITHM 2/
% results – post check if found fprintf ('Target value found in position %i', i-1); else fprintf ('Target value not found'); end
size=6; % Size of the vector list= randi(50,1,size) % create a vector of random integers list=sort(list)
i = 1 ; found = false; % flag to control if the value is found 0 (false) 1 (true) finished = false; % flag to control if search can be finished
value = input('enter value to search: '); % value to search
while(~found) && (~finished) if (list(i)==value ) found = 1 ; else if ((list(i)>value )||(i==size) ) % i is beyond the position where value should be or i=end of the list finished= true ;% end search else i=i+1; end end end
28
56
31
right
left
left
left
right
right
middle
middle
middle
Target value =
5
1st iteration^5111422^28^3137565970
Target value= (not in the list)
Lefti=1 (^) (left+ right)/2=5^ middle= right= 10
v(middle) = 28 larger than target value, search continues in lower half of the list
left=1 middle = right = (izq+ right)/2 = 2
left=1 right =
middle = (left+ right)/2 = 0
v(middle) = 11 larger than target value, search continues in lower half of the list move right to middle -
left > right empty list, therefore the value is not in the list
5 11 14 22
v(middle) = 5 smaller than target value, search continues in upper half of the list move left to middle + 1
left=2 right= 1 empty list 4th iteration:
2nd iteration
3rd iteration
middle=
% Binary search (sorted lists)
size=6; % Size of the vector
list= randi(50,1,size) % create a vector of random integers
list=sort(list);
% initialization
found = false; % flag to control if the value is found false/true
position=-1; %position of the value sought, initialized to -
left = int16(1); % lower limit (left) of subsist
right = int16(size); % upper limit (right) of sub list
middle=idivide(left+right,2); % idivide = integer division