Four search algorithms for data structure and algorithm

Source: Internet
Author: User

Goal

In this chapter, you'll learn to search for data using linear search techniques and two-fork search techniques to search for data

Linear Search:is the simplest method of searching,also known as sequential search,include the item to be compared with the entries in the list,linear search is done by comparing the required elements with the first element in the list.

if the values do not match:The desired element is compared to the second element in the list. If the value still does not match:The required element is compared to the third element in the list. This process will continue until:find the desired element or reach the end of the list. use a linear search algorithm to write an algorithm to search for Employee Record Listwork number for the given employee:1.read the work number to be searched    (First, determine the number of the job you're looking for.)2.Seti = 0 Nis the maximum value subscript for the array(Upper Bounds)3.Repeat steps4untili > NorArr[i] = employee ID4.IValue Increase15.ifi > N:           Show"not found"     otherwise           Show"have been found"

The efficiency of the search algorithm is determined by the running time of the algorithm. in the best case scenario:the element is in the first position of the list. the number of comparisons is1. The best efficiency of linear search isO (1). in the worst case scenario:ElementsAt the last position in the list or it doesn't exist in the list at all. the number of times the comparison is an element. the worst efficiency of linear search isO (n).

in the average case:The average number of comparisons for a linear search is determined by the average comparison in the best and worst searches. the average efficiency of a linear search is(n + 1).


thinking during recess

you want to include in a theto search for an element by applying a linear search in an array of elements, if the searchFinally, you find that the element is not in the array, in order to search for the desired element in that given list, you want toHow many times do you compare?


Answer:5,000


Problem Description:Write a program that contains the most -The array of numbers uses a linear search algorithm to search for a given number of programs,If the element you are searching for appears more than once in the list, the program should show where it first appears andthe total number of comparisons made should be displayed.


Two-fork search algorithm:for a large list of searches,search for data with very few comparisons,You can use the two-fork search algorithm as long as the list you want to search is sortedconsider an example. you want to search for names in alphabetical phone directoriesSteve. to search for names using the two-fork search algorithmSteve:Open the phone directory in the middle to determine which half contains the name. Open in the middle of that half to determine which half contains the name. Repeat this process until you find the name you want. Two-fork search reduces the search page by half each time.

write an algorithm to implement a two-fork search algorithm. 1.accept the element you want to search (determine the value to find)2.Setlowerbound = 03.Setupperbound = n–14.Setmid = (lowerbound + upperbound)/25.ifArr[mid] =Required elements:A.Show"have been found"B.go to stepTen6.if the desired element< Arr[mid]:A.Setupperbound = mid–1

7.if the desired element> Arr[mid]:A.SetLowerbound = mid + 18.iflowerbound <= upperbound:A.go to step49.Show"not found".Exit

In each step of the binary search algorithm, the search area is halved. The best case for this algorithm is if the element to be searched is exactly in the middle of the list:The number of comparisons for this condition is1. in the worst case, the desired element is not found in the list:after the first pair of points, the search space is reduced toN/2elements, whereNis the number of elements in the original list. after the second pair of points, the search space is reduced toN/4, i.e.N/22an element. after the firstIafter the sub-score, the search space is reduced ton/2ielement.

thinking during recess

in the ___________in the search algorithm, you start at one end of the list and scan the entire list until you find theItem or the end of the arrival list.


Answer:Linearto perform __________search algorithm, the list should be sorted. Answer:Two forks
Problem Description:Write a program that uses a two-fork search to contain the most -to search for a number in an array of elements, assumingthe array elements are entered in ascending order. If there are multiple numbers in the array to search for, a match is foundthe rope stopped. The program should also show the total number of comparisons made.

Summaryin this chapter, you have learned:the best efficiency for linear search isO (1), worst efficiencyO (n). to apply a binary search algorithm, you should ensure that the list you are searching for is out of order. the best efficiency for a two-fork search isO (1), the worst efficiency isO (log n).
/* Find a number from 8 numbers */using system;class ban{public static void Main (String[]args) {//int []arr={ 8001,8002,8003,8004,8007,8010,8005,8009}; Defines an array of 8 integers Console.WriteLine ("Please enter your number of work number:"); int n; n the upper bound of the array N=convert.toint32 (Console.ReadLine ());//n is the length (number) of the arrays int []arr=new int[n];//defines an array of 10 numbers for (int j=0;j<n ; j + +) {Console.Write ("Please enter" + (j+1).) ToString () + "number:"); Arr[j]=convert.toint32 (Console.ReadLine ());} 3. Repeat step 4 until i > N or arr[i] = ID to exit. Char ch= ' y '; Define the conditions we are constantly looking for, if y| Y, then always look for; n|  N: Exits the lookup. while ((ch== ' y ') | | (ch== ' Y ')) {Console.WriteLine ("Please enter the number you want to find:"); int Id=convert.toint32 (Console.ReadLine ());//define the data element to find int lowerbound=0;int upperbound=n-1;int mid= (lowerbound+ Upperbound)/2;//Intermediate value subscript//13 while (lowerbound<=upperbound)//implementation find the appropriate median index {if (Id<arr[mid]) upperbound=mid-1; Elselowerbound=mid+1;mid= (Lowerbound+upperbound)/2; Console.WriteLine ("Low:" +lowerbound+ "Mid:" +mid+ "Upper:" +upperbound);} For data elements found, code Console.WriteLine (Arr[mid]), if (Id==arr[mid]) Console.WriteLine ("OK"); Elseconsole.writeline ("No found ...."); COnsole. WriteLine ("Do you want to continue looking, yes (y| Y), no (n|  N): "); Ch=convert.tochar (Console.ReadLine ());} Keep looking for End}}


/* Use a two-fork search to search for a number in an array containing up to 20 elements, assuming the array is entered in ascending order. If there are multiple numbers to search in the array, a match is found and the search stops. The program should also show the total number of comparisons made. */using system;class binarysearch{static void Main (String[]args) {int[]arr=new int[20];//the array to search for int n;//The number of elements in the array int i;// Gets the number of elements stored in the array while (true) {Console.Write ("Enter the number of elements of the array:"); string S=console.readline (); N=int32.parse (s); if (n>0) && (n<=20)) break;elseconsole.writeline ("\ n array minimum of 1 elements, up to 20 elements. \ n"); Accepts the array element Console.WriteLine ("------------------------------------------"); Console.WriteLine ("---------------Input array element---------------"); Console.WriteLine ("------------------------------------------"); for (i=0;i<n;i++) {Console.Write ("<" + (I+1) + ">"); string S1=console.readline (); Arr[i]=int32.parse (S1);} Char ch= ' y ';d o{//the number of Console.Write to search ("Please type the number you are looking for"); int Item=convert.toint32 (Console.ReadLine ());//apply binary search int Lowerbound=0;int upperbound=n-1;//Gets the index of the intermediate element int mid= (lowerbound+upperbound)/2;int ctr=1;while ((Item!=arr[mid]) && (Lowerbound<=upperbound)//Search the array for the element's loop {if (Item>arr[mid]) lowerbound=mid+1;elseupperBound=mid-1;mid= (Lowerbound+upperbound)/2;//ctr++;} if (Item==arr[mid]) console.write ("\ n" +item. ToString () + "found location:" + (mid+1). ToString ()); Elseconsole.write ("\ n" +item. ToString () + "not found in array"); Console.Write ("\ n number of comparisons:" +ctr); Console.Write ("\ n continue search (y/n)"); Ch=char. Parse (Console.ReadLine ());} while ((ch== ' y ') | | (ch== ' Y '));}}

/* Write a program that uses a given number of linear search algorithms in a number of 20 numbers, and if the element to be searched appears more than once in the list, the program should show where it first appears and should also show the total number of comparisons made. */using system;class sequentialsearch{static void Main (String[]args) {int[]arr=new int[20];//to search for an array of int n;//an element in an array int i ;//Gets the element stored in the array while (true) {Console.Write ("Enter the number of elements of the array:"); string S=console.readline (); N=int32.parse (s); if (n>0) && (n<=20)) break;elseconsole.writeline ("\ n array minimum of 1 elements, up to 20 elements. \ n"); Accepts the array element Console.WriteLine ("------------------------------------------"); Console.WriteLine ("---------------Input array element---------------"); Console.WriteLine ("------------------------------------------"); for (i=0;i<n;i++) {Console.Write ("<" + (I+1) + ">"); string S1=console.readline (); Arr[i]=int32.parse (S1);} Char ch= ' y '; int ctr;do{//accept the number of Console.Write to search ("\ n Please enter the number you want to search:"); int Item=convert.toint32 (Console.ReadLine ());// Apply linear search Ctr=0;for (i=0;i<n;i++) {ctr++;if (Arr[i]==item) {Console.WriteLine ("\ n" +item. ToString () + "found in position" + (i+1). ToString ()); break;}} if (i==n) {Console.WriteLine ("\ n" +item. ToString () + "no element found in array"); Console.writeliNE ("\ n the number of comparisons:" +ctr); Console.Write ("\ n continue search (y/n):"); Ch=char.parse (Console.ReadLine ());}} while ((ch== ' Y ') | | (ch== ' y '));}}


Four search algorithms for data structure and algorithm

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.