Fastest sorting and searching algorithm for the simplest code to achieve __ algorithm

Source: Internet
Author: User
Tags integer division

The simplest code implementation of the fastest sorting and searching algorithm


by http://blog.csdn.net/shendl/ Preface

The core problem of the algorithm is sorting and searching. These 2 fields are the most widely used and are the most thoroughly studied. In this article I will explain the most efficient two algorithms for sorting and searching: A fast sort algorithm and a binary search algorithm.

Textbooks and a lot of implementation library to give the two algorithms of the code is very complex, it is difficult to understand, this article I give the code is the simplest implementation code, easy to understand, high efficiency.

Origin

Just now someone asked me how to achieve a quick sort, I wrote a quick sort of Java code within 5 minutes, wondering if they understood.

So I thought about writing this article. The simplest implementation of the fast sorting algorithm and the binary search algorithm is introduced.

My binary search algorithm was implemented when I developed the Workflow editor with Flex. The requirement at the time was to draw a connector between 2 graphs, which required a mouse operation, and that the starting and ending points of the lines were on the outer frame of the graphic.

The above description may be more abstract, so to speak, 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 segment. However, such segments are ugly, the customer requires that the two ends of the line should be on the 2-box border.

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

At that time the binary search algorithm was written in ACTIONSCRIPT3, and now I changed it to Java.

fast sorting algorithm and binary search algorithm

The algorithm mainly divides into the sorting algorithm, the search algorithm, the graph algorithm. Graph algorithm I do not use much, have no say, this article will not say.

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

Because, they are implemented using recursion, the code is concise and clear, efficient and very high.

According to my understanding, the essence of the algorithm is mathematics. According to the input and set goals, the output is implemented with limited steps. In general, the use of computer-implemented algorithms, will use the loop, so as to play the advantages of computer high-speed operation.

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

1, recursive code is much simpler and more elegant than the loop.

2, recursive code can be modeled mathematically, and its correctness can be verified mathematically.

Many functional languages do not even have the concept of looping and keywords, forcing you to use recursive return to implement loops. For example, ErLang.

Recursion also has some drawbacks, recursive use of stacks to save function addresses and parameters, return values, and the stack is a certain size, too many recursive calls can cause stack overflow.

However, recursive algorithms can easily be converted into loops. I appreciate the simplicity of recursion, and I don't use loops unless there's really a stack overflow problem.

Two-point search algorithm Theory:

The binary search algorithm is used to search for sorted collections.

The principle of this is:

1, locate the intermediate element of the sorted array, and if it matches the target value, returns its index in the array.

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

If the median value is larger than the target value, the process is recursively 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 that it was not found.

4, if the child set has 2 elements, then each compares. Because the integer division of Java discards decimals, if the array has only 2 elements, then the middle value is always the first element.

The recursive procedure above will eventually return the index of the matching element, or-1, indicating that it is not found.

The binary search algorithm is fast because it can divide the array into two halves at a time, and each recursive call can remove half of the data without matching each data.

Code:

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

/**

* By Liang Shao http://blog.csdn.net/shendl/

*@param Array

*@param start

*@param End This is the index of the last element, 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;

Elseif(array[end]==value) {

return end;

}

Elseif(array[middle]==value) {

return middle;

Elseif(Value>array[middle]) {

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

Elseif(Value<array[middle]) {

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

}

return-1;

}

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

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? Simple, first use a quick sort algorithm to sort, and then search with a binary search.

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

Theory:

The slowest and easiest sort algorithm to think about is the Insert sort algorithm:

1, iterate over the array, find the smallest element, and put it in the first element.

2, loop through the unordered array until the entire array is sorted.

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

The efficient way to insert a sort is because to find the smallest amount of data in the entire array, you need to traverse the elements of the entire array.

And the insert sort of smart is smart in it does not look for the entire array smallest, second small ... element, instead of moving the value less than an element to one side at a time, the final automatic sorting is done through the iteration. This greatly saves the computational steps required for sorting.

The theory of the fast sort algorithm:

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

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

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

4, return L and R.

We use Java in the way of in-place sorting, so we don't need to return a value.

Because Java is a language that can modify variables, in functional language terms, there are "side effects." We use this side effect to directly modify the array as a parameter and do not need to return a value.

Code:

/** by Liang Shao http://blog.csdn.net/shendl/

* Quick sort, with side effects from small to large

*@param Array

*@param start

*@param End This is the index of the last element, 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 because the recursive call j+1, may cause the J than end 1 larger. In addition, this can happen 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 the token 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;

}

}

Swap the element position of the tag element and the first >= it, 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 also uses a quick sort algorithm for sorting. But its code is written like a heavenly book.

The main method to improve the execution efficiency of the fast sorting algorithm is to detect the center point, hoping that the center point of the selection will have a greater probability of being the median of the whole array.

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

Note that one of the implementation techniques above is to implement an in-place comparison of the arrays by moving the central data elements to the end of the array. This is a more commonly used technique to move data to the front or end of the array to facilitate comparison of data.

In addition, my Java Quick sort code uses "side effects", whereas in a purely functional language, such as Haskell,erlang, there is no "side effect", which means that the variable cannot be assigned a value. You need to return the value at this time, creating a new child array each time. But the function language array processing function is very strong, also can do many performance optimization, therefore the functional language realizes the fast sorting code to be simpler, has no "side effect", also is more mathematical.

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

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.