The simplest code implementations of the fastest sorting and searching algorithms _ Go

Source: Internet
Author: User
Tags integer division

Turn from: 4053853

Objective

The core problem of the algorithm is sorting and searching. These 2 areas are the most widely used and the most researched. In this article I will explain the two most efficient algorithms in the field of sorting and searching: The fast sorting algorithm and the binary search algorithm.

The code of the two algorithms given by the textbook and many implementation libraries is very complex and difficult to understand, and the code I give in this article is the simplest implementation code, easy to understand, and highly efficient.

Origin

Just now someone asked me how to achieve a quick sort, I wrote a quick sort of Java code in 5 minutes and didn't know if they understood.

So, I thought about writing this article. This paper introduces the simplest implementation of fast sorting algorithm and binary search algorithm.

My binary search algorithm was implemented when I developed the Workflow editor with Flex. The requirement at the time was to draw a link between the 2 graphs, which required to be drawn according to the mouse action, and the beginning and end of the line were on the outer frame of the shape.

The above description may be more abstract, so to speak, originally I realized the GUI effect is, 2 boxes, using the mouse to connect them, I draw the line is mouse punctuation and release the 2 endpoints connected to the line. However, such segments are ugly, and customers require that the two ends of the segment should be on the 2-box border.

How to solve this problem? I think of the line segment as a collection of sorted points, and then I can use the binary search algorithm to search for the intersection of the segment and the border, and then draw them out.

The binary search algorithm was written in ACTIONSCRIPT3, and now I've changed it to Java.

Fast sorting algorithm and binary search algorithm

The algorithm is mainly divided into sorting algorithm, search algorithm and graph algorithm. The graph algorithm I use not much, does not have the voice, this article does not say.

The quickest of the sorting algorithm is the fast sorting algorithm, and the fastest one in the search algorithm is the binary search algorithm. I also like these 2 algorithms best.

Because they are implemented recursively, the code is simple, clear, and highly efficient.

According to my understanding, the essence of the algorithm is mathematics. Based on the input and set targets, the output is implemented in a limited number of steps. Usually, the use of computer-implemented algorithms, will use the loop, so as to give full play to the advantages of computer high-speed computing.

Loops and recursion are equivalent, which have been proven by scientists. There are no loops in mathematics, only the concept of recursion, so there are many advantages to using recursion instead of a cyclic representation algorithm:

1, recursive code is much more concise than the loop, but also a lot more elegant.

2, the recursive code can be modeled mathematically, and the correctness can be verified from a mathematical perspective.

Many functional languages do not even have looping concepts and keywords that force you to use recursion to implement loops. For example, ErLang.

Recursion also has some drawbacks, recursive use of the stack to save the function address and parameters, return value, and the stack is a certain size, too many recursive calls may cause stack overflow.

However, recursive algorithms can easily be turned into loops. I appreciate the simplicity of recursion, and I'm not going to use loops unless there really is a stack overflow problem.

Theory of binary search algorithm:

A binary search algorithm is used to search for a sorted collection.

The principle of this is:

1, the middle element of the sorted array is found, and if it matches the target value, it returns its index in the array.

2, if not found, then determine the median value is larger or smaller than the target value,

If the median value is larger than the target value, then the process is recursive for the first element to the middle-1 element.

If the median value is smaller than the target value, then the middle+1 to the last element.

3, if the end index is less than the starting index, returns-1, indicating no found.

4, if the sub-collection has 2 elements, then compare each one. Because the integer division of Java discards decimals, if the array has only 2 elements, then the middle value is always the first element.

After this recursive procedure, the index of the matching element is returned, or 1, indicating that it is not found.

The binary search algorithm is fast because it divides the array into two halves at a time, eliminating half of the data per recursive call, rather than matching every data.

Code:

Here is the code, the logic is clear, the code is simple.

/**

* by Shen Dongliang/Liang http://blog.csdn.net/shendl/

* @param array

* @param start

* @param end This is the index of the last element, and the first call should be array.length-1

* @param value

* @return

*/

public static int BinarySearch (int[] array,int start,int end,int value) {

int middle= (start+end)/2;

if (End<start) {

return-1;

}

if (end== (start+1)) {

if (Array[start]==value) {

return start;

}else if (array[end]==value) {

return end;

}

}else if (array[middle]==value) {

return middle;

}else if (Value>array[middle]) {

return BinarySearch (Array,middle+1,end,value);

}else if (Value<array[middle]) {

return BinarySearch (Array,start,middle-1,value);

}

return-1;

}

The above code is slightly changed to sort any type. If you use generics, and then add the implementation to the comparable interface, you can.

Fast sorting algorithm

The binary search algorithm is really fast, but it can only be used for sorted arrays. What if the array is not sorted? Simply, sort by using a quick sort algorithm, and then search with a binary search.

Sorting and then searching is much faster than matching each element. Search engines, database indexes also use a sorting technique for data sets, so that searching data is fast.

Theory:

The slowest and most easily thought-out sort algorithm is the Insert sort algorithm:

1, iterate through the array, find the smallest element, and put it to the first element.

2, the loop looks for unsorted arrays until the entire array is sorted.

This requires 2 nested loops, which means that its efficiency is O (n^2);

The efficiency of inserting a sort is so much the fact that to find the smallest data in the entire array, you need to traverse the elements of the entire array.

And the insertion sort is smart in that it does not look for the entire array smallest, minor ... element, instead of just moving the value less than an element to one side at a time, the order is eventually automatically implemented by iteration. This greatly saves the calculation steps required for sorting.

Theory of the Fast sorting algorithm:

1, if the number of elements in S is 0 or 1, then return.

2, select any element in S, V, called the center point.

3, the elements in the S collection are divided into 2 parts: l={elements less than pivot + pivot} and r={are greater than or equal to pivot elements}.

4, return L and R.

We use Java in an in-place sort order, so we don't need to return a value.

Because Java is a language in which variables can be modified, there are "side effects" in terms of functional languages. We use this side effect to modify the array directly as a parameter, without the need to return a value.

Code:

/** by Shen Dongliang/Liang http://blog.csdn.net/shendl/

* Quick sorting, with side effects from small to large

* @param array

* @param start

* @param end This is the index of the last element, and the first call should be array.length-1

*/

public static void QuickSort (int[] array,int Start,int end) {

It is possible to cause start>end to be j+1 by recursive invocation, which may cause J to be 1 larger than end. Also, if the array is empty, or if an input error occurs

if (End<=start) {

Return

}else {

Take the middle element as the center point and move to the far right

int sign= (start+end)/2;

int Tmp=array[end];

Array[end]=array[sign];

array[sign]=tmp;

int J=start;

for (int i=start;i<=end-1;i++) {

Less than the element and tag interchange, equal to not interchangeable, otherwise it will form a dead loop

if (Array[i]<array[end]) {

Tmp=array[i];

ARRAY[I]=ARRAY[J];

array[j]=tmp;

j=j+1;

}

}

Swaps the markup element with the first >= its element position so that the array is divided into 2 parts, one part smaller than the center value, and one part larger than the center value.

TMP=ARRAY[J];

Array[j]=array[end];

array[end]=tmp;

QuickSort (ARRAY,START,J);

QuickSort (Array,j+1,end);

}

}

The Java arrays class is also sorted using the Quick sort algorithm. But its code is written like a heavenly book.

The main way to improve the execution efficiency of the fast sorting algorithm is to detect the center point, and hopefully the center point of the selection has a greater probability of being the median of the entire array.

In my implementation, simply select the middle value of the array as the center point, in general, the efficiency of this choice is good.

Note that one of the implementation techniques above implements an in-place comparison of arrays by moving the central data element to the end of the array. This is a more common technique of moving data to the front or the end of an array to make it easier to compare data.

In addition, my Java Quick sort code uses "side effects", whereas in purely functional languages, such as Haskell,erlang, there are no "side effects", which means that variables cannot be re-assigned. You need to return a value at this point, creating a new sub-array each time. But the function language array processing function is very strong, also will do many performance optimizations, therefore the function language realizes the quick sorting code to be simpler, does not have "the side effect", also is more mathematically.

The JDK uses the binary search and the fast sorting algorithm to realize the search and the sorting, which is the performance advantage of the above two algorithms.

The simplest code implementations of the fastest sorting and searching algorithms _ Go

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.