Search and sort 02, half search, search sort 02 half

Source: Internet
Author: User

Search and sort 02, half search, search sort 02 half

Semi-query is also called binary search. When an element is searched in an array or set, an intermediate element is located first. If the element to be searched is exactly the same as the element in the intermediate position, match elements can be found through one query. If the element to be searched is smaller than the element in the middle position, the element in the latter half is discarded and the element in the former half is located, this is repeated until the matching element is found. If the element to be searched is greater than the element in the middle position, the first half of the element is discarded and the middle position element is located in the later half of the element, this is repeated.

 

The first question is: how to locate the intermediate position element? In semi-query, it is stipulated that when the number of elements is an odd number, for example, there are three elements, the element in the middle is an element with an index of 1; when the number of elements is an even number, for example, there are four elements, element theories with indexes of 1 and 2 are both intermediate position elements. However, in semi-query, the elements with indexes of 2 are regarded as intermediate position elements.

 

The second problem is that the elements to be searched need to be compared with the elements at the intermediate position. Before comparison, we must sort the arrays in ascending or descending order.

 

Defines a class that maintains an array of int [] type. It determines the array length and sorts the array by using the constructor, and provides the method of printing array elements and a half-fold algorithm.

    public class MyArray
    {
Private int [] arr; // an array is maintained internally.
Private static Random r = new Random (); // use it to generate Random elements of the array
// The constructor is used to determine the length of the internal array, generate random elements of the array, and sort the array elements.
        public MyArray(int size)
        {
            arr = new int[size];
            for (int i = 0; i < size; i++)
            {
                arr[i] = r.Next(1, 100);
            }
            Array.Sort(arr);
        }
// Returns the index position of the search element.
        public int HalfSearch(int key)
        {
Int low = 0; // low point. The initial value is set to the lowest point, that is, index 0.
Int high = arr. Length-1; // high point. The initial value is set to the highest point, that is, the last position of the index array.
// If the number of elements in the array is an even number, for example, four indexes 2 and 3 are in the middle, use the following algorithm to point to index 3.
// If the number of array elements is an odd number, for example, 3, Index 1 is the center position, use the following algorithm to point to index 1.
            int middle = (low + high + 1)/2;
Int location =-1; // if no value is found,-1 is returned.
// Loop. Keep searching if it is not found
            do
            {
// Print the elements at the low point and high point in each loop.
                Console.WriteLine(PrintSectionElements(low, high));
                Console.WriteLine();
// If you want to find the element at the intermediate position, the index at the intermediate position is returned.
                if (key == arr[middle])
                {
                    location = middle;
                }
Else if (key <arr [middle]) // if you want to find the element smaller than the intermediate element, set the index before the intermediate position to a high point
                {
                    high = middle - 1;
                }
Else // if you want to find that the element is greater than the element at the intermediate position, set the index after the intermediate position to a low point.
                {
                    low = middle + 1;
                }
// If the code runs here, it indicates that no matching element has been found. Because the previous settings reset the low or high point, you must reset the intermediate position here.
                middle = (low + high + 1)/2;
            } while ((low <= high) && (location == -1));
            return location;
        }
// Print the array elements between two locations
        public string PrintSectionElements(int low, int high)
        {
            string temp = "";
// Print the element between two positions and keep it with a space
            for (int i = low; i <= high; i++)
            {
                temp += arr[i] + " ";
            }
            return temp;
        }
// Rewrite the ToString method to print all elements of the array.
        public override string ToString()
        {
            return PrintSectionElements(0, arr.Length - 1);
        }
    }

In the preceding section, the half-fold search aims to locate the index position of the matching element in the array. Therefore, by comparing the size of the matching element and the element in the intermediate position, we constantly adjust the low, high, and intermediate positions. In C #, 1/2 of the result is 0.

 

Client.

    class Program
    {
Private static int key; // The element to be searched
Private static int position; // the position where the matching element is located.
        static void Main(string[] args)
        {
            MyArray myArray = new MyArray(7);
// Print all elements
            Console.WriteLine(myArray);
Console. WriteLine ("Enter the element to be searched or enter-1 to exit ");
            key = Convert.ToInt32(Console.ReadLine());
            Console.WriteLine();
            while (key != -1)
            {
// Call the half-fold algorithm to locate the desired Element
                position = myArray.HalfSearch(key);
If (position =-1) // The element to be matched is not found.
                {
Console. WriteLine ("No element {0}", key found );
                }
                else
                {
Console. WriteLine ("element {1} found at position {0}", position, key );
                }
Console. WriteLine ("Enter the element to be searched or enter-1 to exit ");
                key = Convert.ToInt32(Console.ReadLine());
                Console.WriteLine();
            }
        }
    }

 

Describe the efficiency of semi-query with time complexity

Assume that an array has 1023 elements. Since it can be expressed as "1023 = 2 records-1", all n = 10. If you perform a half-fold operation on the array, divide it by 2. That is to say, you can search for an element in the array. The matching element can be found up to 10 times.

 

For the expression "2 between-1", if n = 30, it indicates 1 billion. If you use a half-fold query, the matching element can be found up to 30 times for the 1 billion elements. Linear search requires an average of 0.5 billion queries. The efficiency of the two algorithms is evident.

 

Write the time complexity of semi-query and binary query as O (log n), which is called "logarithm running time" and reads as "logarithm level ".

 

The "Search and sorting" series include:

Search and sorting 01, linear search, time complexity, algorithm search and sorting 02, half-lookup and sorting 03, select sorting search and sorting 04, insert sorting
First sort and then use the half lookup method to find numbers

Your program has an endless loop. When this number is not available
If (n> a [c]) d = c + 1;
If (n <a [c]) B = c + 1;
D = C-1!
Another point is to change it to if (B> = d) when determining whether there is such a number!

Perform semi-query and simple sorting in the sequence table

Sort:
# Include <stdio. h>
# Define N 10

Void Display (int * a, int n)
{
Int I;
For (I = 0; I <n; I ++ ){
Printf ("% d", a [I]);
}
Printf ("\ n ");
}

Void SelectionSort (int * a, int n)
{
Int I, j, index, value;

For (I = 0; I <n-1; I ++ ){
Index = I;
Value = a [I];
For (j = I + 1; j <n; j ++)
If (value> a [j]) {
Index = j;
Value = a [j];
}
A [index] = a [I];
A [I] = value;
Display (a, n );
}
}

Void main ()
{
Int a [N], I;
For (I = 0; I <N; I ++)
A [I] = N-I;
Display (a, N );
SelectionSort (a, N );
}
Half lookup:
Int binarysearch (int number)
{
Int mid, start = 0, end = LEN-1;

/* Assume that a is sorted */
/* Mustbe (start, end, number), because a [start... end] is the entire array a [0 .. LEN-1] */
While (start <= end ){
/* Mustbe (start, end, number), because it is correct at the beginning of the cycle, and this condition is maintained for each loop */
Mid = (start + end)/2; // obtain the value in the middle of array a, compared with number
If (a [mid] <number)
/* If the median value of array a is smaller than number, the number must be in the second half of the mid array. Therefore, we will use mid + 1 as the start, number must be in the second half of array a [mid + 1, end */
Start = mid + 1;

Else if (a [mid]> number)
/If the median value of array a is greater than number, the number must be in the first half of the array before the mid, this mid-1 is the last element of the first half of the array */
End = mid-1;
Else
/* A [mid] = number, indicating that */is found */
Return mid;
}
/*
* Mustbe (start, end, number) has been cyclically maintained. It should still be established here. There must be no number outside the range of a [start... end,
* ...... Remaining full text>

Related Article

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.