Ordered linear searching (sorted/ordered Linear search)

Source: Internet
Author: User

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)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.