Simplest code implementation of the fastest sorting and search algorithms

Source: Internet
Author: User
Tags integer division
Document directory
  • Theory:
  • Code:
  • Theory:
  • Code:


Simplest code implementation of the fastest sorting and search algorithms

By Shen Dongliang


The core issue of algorithms is sorting and searching. These two fields are the most widely used and thoroughly studied. In this article, I will explain the two most efficient algorithms in the sorting and search fields: quick sorting and binary search.

The Code of these two algorithms provided by textbooks and many implementation libraries is very complex and difficult to understand. The code I provided in this article is the simplest implementation code, which is easy to understand and highly efficient.




Someone asked me how to implement quick sorting. I wrote a Java code for quick sorting within five minutes. I don't know if they understand it.

Therefore, I want to write this article. This section describes the simplest implementation of the quick sorting algorithm and binary search algorithm.

My binary search algorithm was implemented when I used flex to develop a Workflow Editor. At that time, we needed to draw a connection line between the two images. We needed to draw lines based on the mouse operation, and the start and end points of the line segments were on the outer frame of the image.

The above description may be abstract. In this case, the original GUI effect I implemented is that two boxes are connected with the mouse, the line I draw is a line that is connected to the two endpoints by clicking the mouse. However, such a line segment is ugly. The customer requires that the two sides of the line segment be on the border of two boxes.

How can this problem be solved? I think of a line segment as a set of sorted points. Then I can use the binary search algorithm to search for the intersection between the line segment and the border and draw them out.

At that time, the binary search algorithm was written in actionscript3. Now I have changed it to Java.


Quick Sorting Algorithm and Binary Search Algorithm

Algorithms include sorting algorithms, search algorithms, and graph algorithms. I am not using graph algorithms much and have no right to speak. I will not talk about this article.

The fastest sorting algorithm is the quick sorting algorithm, and the fastest searching algorithm is the binary search algorithm. I also like these two algorithms best.

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

According to my understanding, the essence of an algorithm is mathematics. Use limited steps to achieve output based on input and set goals. Generally, computation algorithms use loops to take advantage of high-speed computation.

Loops are equivalent to recursion, which has been proved by scientists. There is no loop in mathematics and only the concept of recursion. Therefore, there are many advantages to use recursion instead of loop to represent an algorithm:

1. Recursive code is much simpler and more elegant than loop code.

2. Recursive code can be modeled in mathematics, and its correctness can be verified in mathematics.

Many functional languages do not even have the concept and Keywords of loops, forcing you to use recursion to implement loops. For example, Erlang.

Recursion also has some disadvantages. recursion uses stacks to store function addresses, parameters, and return values, while stacks have a certain size. Excessive recursive calls may cause stack overflow.

However, recursive algorithms are easily converted into loops. I prefer recursive conciseness. Unless stack overflow occurs, I will not use loops.


Binary Search Algorithm Theory:

The binary search algorithm is used to search sorted sets.

The principle is:

1. Find the intermediate element of the sort array. If it matches the target value, it returns its index in the array.

2. If no value is found, determine whether the median value is larger or smaller than the target value,

If the median value is greater than the target value, recursion is performed on the elements from the first element to middle-1.

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

3. If the ending index is smaller than the starting index,-1 is returned, indicating that no index is found.

4. If the child set has two elements, compare them. Because the integer division in Java discards decimals. If the array has only two elements, the value of the middle is always the first element.

After the above recursive process, the index of the matching element will be returned, or-1, indicating that it cannot be found.


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



The following is the code with clear logic and simple code.


* By Shen Dongliang/Liang Shao

*@ ParamArray

*@ ParamStart

*@ ParamEnd: This is the index of the last element. The first call should be array. Length-1.

*@ ParamValue

*@ Return


Public Static IntBinarysearch (Int[] Array,IntStart,IntEnd,IntValue ){

IntMiddle = (start + end)/2;

If(End <start ){



If(END = (start + 1 )){

If(Array [start] = value ){


}Else If(Array [end] = value ){



}Else If(Array [Middle] = value ){


}Else If(Value> array [Middle]) {

Return Binarysearch(Array, middle + 1, end, value );

}Else If(Value <array [Middle]) {

Return Binarysearch(Array, start, middle-1, value );





The above code can be sorted by any type with slight changes. For example, you can add the comparable interface implementation to the generic interface.


Quick Sorting Algorithm

The binary search algorithm is indeed very fast, but it can only be used for sorted arrays. What if the array is not sorted? Simple: Use the quick sorting algorithm for sorting, and then use binary search for searching.

Sorting and searching are much faster than matching each element. Search engines and database indexes also use the Sorting Technology for data sets so that data can be searched quickly.



The slowest and most easy-to-think sorting algorithm is insert Sorting Algorithm:

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

2. Search for unordered arrays in a loop until the entire array is sorted.

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

The efficiency of insertion sorting is so high that the elements of the entire array need to be traversed to find the smallest data in the entire array.

The smart way to insert sorting is that it does not look for the minimum and minimum number of times of the entire array... Instead, only the values smaller than a specific element are moved to one side each time, and the sorting is automatically implemented through iteration. This greatly saves the computing steps required for sorting.


Theory of the Quick Sort Algorithm:

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

2. Select any element V in S, which is called the center point.

3. Divide the elements in the s set into two parts: L = {elements less than limit + limit} and r = {elements greater than or equal to limit }.

4. Return L and R.

Java is used to sort data locally, so no return value is required.

Java is a language that can modify variables. In functional languages, it has "Side effects ". We use this side effect to directly modify the array as the parameter and do not need to return the value.




/** By Shen Dongliang/Liang Shao

* Fast sorting with side effects from small to large

*@ ParamArray

*@ ParamStart

*@ ParamEnd: This is the index of the last element. The first call should be array. Length-1.


Public Static VoidQuicksort (Int[] Array,IntStart,IntEnd ){

// Start> end may be caused by J + 1 during recursive calling, which may cause J to be 1 larger than end. This also happens if the array is empty or the input is incorrect.

If(End <= Start ){



// Take the middle element as the center point and move it to the rightmost side.

IntSign = (start + end)/2;

IntTMP = array [end];

Array [end] = array [sign];

Array [sign] = TMP;

IntJ = start;

For(IntI = start; I <= end-1; I ++ ){

// Elements and tags smaller than are interchangeable. equal elements cannot be exchanged. Otherwise, an endless loop is formed.

If(Array [I] <array [end]) {

TMP = array [I];

Array [I] = array [J];

Array [J] = TMP;

J = J + 1;



// Swap the positions of the marked element and the first element> =, so that the array is divided into two parts. One part is smaller than the center value, and the other part is greater than the center value.

TMP = array [J];

Array [J] = array [end];

Array [end] = TMP;

Quicksort(Array, start, J );

Quicksort(Array, J + 1, end );




The arrays class of Java also uses the quick sorting algorithm for sorting. But its code is like tianshu.


The main method to improve the efficiency of the Quick Sort Algorithm is to detect the center point. It is expected that the selected center point has a greater probability that it is the value of the entire array.

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


Note that the above implementation technology, we use the method of moving the central data element to the end of the array to achieve the local comparison of the array. This is a commonly used technology. It moves data to the beginning or end of the array to facilitate data comparison.


In addition, my java quick sorting code uses "Side effects", but in pure functional languages such as Haskell and Erlang, there is no "Side effects", that is, variables cannot be assigned a value again. In this case, the return value is required. A new sub-array is created each time. However, the array processing function of functional language is very powerful, and many performance optimizations are also made. Therefore, it is easier to implement fast sorting code without "Side effects" and more mathematical.


JDK uses the binary search and quick sorting algorithms to achieve search and sorting. This shows the performance advantages of the 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: 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.