If the array elements are already sorted (ascending), then we do not have to traverse the entire array to search for an element. In the algorithm code given below, to any point, assuming that the current Arr[i] value is greater than the value of the search data, you can stop the search.
#include <stdio.h>//a function to search "data" under an array "arr" of size "size"//returns 1 if the element is present else 0intOrderedlinearsearch (intArr[],intSizeintdata) { intFound_flag =0; inti; for(i=0; i<size;i++) { //loop through the entire array and search for the element if(Arr[i] = =data) { //if the element is found, we change the flag and break the loopFound_flag =1; Break; } //Here's an additional check Else if(Arr[i] >data) Break; } returnFound_flag;} //driver program to test the functionintMainvoid){ intarr[Ten] = {2,6,4,Ten,8,1,9,5,3,7}; intTo_search =5; if(Orderedlinearsearch (arr,Ten, To_search)) printf ("FOUND"); Elseprintf ("Not FOUND"); return 0;}
The time complexity of the algorithm is O (n). This is because in the worst case we still have to search the entire array. Although the growth rate is the same as disorderly linear search, the complexity is reduced on average.
The space complexity is O (1).
Note: We can also increase the rate of index increase to increase the speed of the algorithm. This reduces the number of comparisons in the algorithm. However, this will have the chance to skip the data you are searching for.
Ordered linear searching (sorted/ordered Linear search)