Those programmers sorting algorithm (on) must master

Today's IT industry is not as good as before the mix, too many employees, resulting in junior programmer surplus, which indirectly led to the company's recruitment increasing the threshold, require the programmer to master the knowledge more and more.
Algorithm is a controversial topic for a long time, the programmer should grasp in the end the algorithm? Different people have different answers, and in fact, many companies have certain requirements for the algorithm, some companies directly during the interview the interviewer will ask questions handwriting algorithm. This technology requires the programmer had a great test, so the face of today's environment, we must master algorithm, in order to occupy a place in future work.
So then, I will briefly explain some sorting algorithm, I hope for your help.

1. Bubble Sort

Bubble Sort (Bubble Sort), is a relatively simple sorting algorithm.
It repeatedly visited elements of the column to sort, in order to compare two adjacent elements, if their order (such as descending, the first letter from A to Z) errors they exchange took over. Working visit element is repeated until there is no need to swap adjacent elements, that is to say the element column has been sorted completed.
The name comes from the fact algorithm larger elements will gradually exchange via a "float" to the top of the column number (ascending or descending order), as if the carbon dioxide bubbles in a carbonated beverage eventually float to the top of the same, hence the name "bubble sort. "
Demo:
Here Insert Picture Description
code is as follows:

@Test
public void bubbleSort() {
    int[] arr = { 3, 44, 38, 5, 47, 15, 36, 26, 27, 2, 46, 4, 19, 50, 48 };
    // 统计比较次数
    int count = 0;
    // 第一轮比较
    for (int i = 0; i < arr.length - 1; i++) {
        // 第二轮比较
        for (int j = 0; j < arr.length - 1 - i; j++) {
            if (arr[j] > arr[j + 1]) {
                // 交换位置
                int temp = arr[j];
                arr[j] = arr[j + 1];
                arr[j + 1] = temp;
            }
            count++;
        }
    }
    System.out.println(Arrays.toString(arr));
    System.out.println("一共比较了:" + count + "次");
}

operation result:

[2, 3, 4, 5, 15, 19, 26, 27, 36, 38, 44, 46, 47, 48, 50]
一共比较了:105次

The code I believe we are able to write, usually bubble sort is written. However, this process has a drawback, is that when the sorting process has been completed will sort the array elements, but this time it will still be to compare, which does no useful work, so that we can optimize this behalf by a boolean variable, above the program that we have come to compare the number of 105 times.
Optimized code:

@Test
public void bubbleSort() {
    int[] arr = { 3, 44, 38, 5, 47, 15, 36, 26, 27, 2, 46, 4, 19, 50, 48 };
    // 统计比较次数
    int count = 0;
    for (int i = 0; i < arr.length - 1; i++) {
        boolean flag = true;
        for (int j = 0; j < arr.length - 1 - i; j++) {
            if (arr[j] > arr[j + 1]) {
                // 交换位置
                int temp = arr[j];
                arr[j] = arr[j + 1];
                arr[j + 1] = temp;
                flag = false;
            }
            count++;
        }
        if(flag) {
            break;
        }
    }
    System.out.println(Arrays.toString(arr));
    System.out.println("一共比较了:" + count + "次");
}

operation result:

[2, 3, 4, 5, 15, 19, 26, 27, 36, 38, 44, 46, 47, 48, 50]
一共比较了:95次

We first define the beginning of the cycle in a boolean variable is true, then if the exchange element, the value will be set to false. So, we can pass this boolean variable to determine whether there are elements of the exchange. If the boolean argument is true, then it proves that there is no element exchange, so long explanation at this time of the array element is already sorted, so you can jump out of the outer loop, otherwise continue ordering. The results can be seen by comparing the number is really reduced a lot.

2. Select Sort

Selection Sort (Selection sort) is a straightforward sorting algorithm. Its working principle is: the first data element to be sorted from the selected minimum (or maximum) of an element stored in the starting position of the sequence, and then to find from the remaining unsorted elements to a minimum (large) elements, and then into the end of the sequence sorted. And so on, until all the number of data elements to be sorted is zero. Select sort is unstable sorting method.
Demo:
Here Insert Picture Description
code is as follows:

@Test
public void SelectionSort() {
    int[] arr = { 3, 44, 38, 5, 47, 15, 36, 26, 27, 2, 46, 4, 19, 50, 48 };
    for (int i = 0; i < arr.length - 1; i++) {
        int index = i;
        for (int j = 1 + i; j < arr.length; j++) {
            if (arr[j] < arr[index]) {
                index = j;// 保存最小元素的下标
            }
        }
        // 此时已经找到最小元素的下标
        // 将最小元素与前面的元素交换
        int temp = arr[index];
        arr[index] = arr[i];
        arr[i] = temp;
    }
    System.out.println(Arrays.toString(arr));
}

operation result:

[2, 3, 4, 5, 15, 19, 26, 27, 36, 38, 44, 46, 47, 48, 50]

Implementation is very simple, first outer loop in the definition of a value stored in the index variable i, which is to avoid repeated comparison, because after each round of comparison, the first i elements already sorted, so no need to compare again, just from the beginning i can. Later comparisons are performed based on the element index position comparison, if the index position of the element after the comparison is the minimum, without exchanging it, you can not move. If the element is smaller than the index position of the element is found, then the index of the element assigned to the index, then the comparison continues until the completion of the comparison, the minimum value of the array index that is obtained after completion of the comparison is that at this time simply position the elements element and i want to exchange index position.

3. Insertion Sort

Insertion sort (Insertion sort) is a straightforward and stable sorting algorithm. If you already have an ordered sequence of data required in this row of good data has been inserted into the sequences of a number, but still requires the insertion of this sequence data ordered, this time is necessary to use a new sorting method - Insert sort, insertion sort basic operation is to have a data into the sorted data in order to obtain a new, plus a number of sequenced data, sorting algorithm is suitable for small amounts of data, the time complexity It is O (n ^ 2). Stable sorting method. Insertion algorithm to sort the array is divided into two parts: the first part contains all the elements of the array, but except for the last element (let the arrays that have a space inserted position), while the second part contains only one element of this (i.e., the element to be inserted). After completion of the first sorting section, then the last element has been inserted into the first portion sorted.
The basic idea is that insertion sort: Each step will be a sort of record, according to the size of the key value is inserted into the previously sorted in place on the array, until all inserted last.
Demo:
Here Insert Picture Description
code is as follows:

@Test
public void InsertionSort() {
    int[] arr = { 3, 44, 38, 5, 47, 15, 36, 26, 27, 2, 46, 4, 19, 50, 48 };
    for (int i = 1; i < arr.length; i++) {
        // 定义待插入的数
        int insertValue = arr[i];
        // 找到待插入数的前一个数的下标
        int insertIndex = i - 1;
        while (insertIndex >= 0 && insertValue < arr[insertIndex]) {
            arr[insertIndex + 1] = arr[insertIndex];
            insertIndex--;
        }
        arr[insertIndex + 1] = insertValue;
    }
    System.out.println(Arrays.toString(arr));
}

operation result:

[2, 3, 4, 5, 15, 19, 26, 27, 36, 38, 44, 46, 47, 48, 50]

So here, because the array element we're not sure, so only the first element of the array is seen as an ordered sequence, so what we need to find the element into position from the start of the second element of the array . Therefore, starting from an outer loop, then arr [i], which is the current saved to the second element, and then locate the first element index of the element to be inserted, i.e. i-1, this time through a while cycle to compare.
When to exit the loop when insertIndex less than 0, because the comparison has been completed and all of the foregoing elements. In the comparison process, if the element to be inserted is smaller than the previous element, a front element will be shifted, i.e. the value of the previous element is directly assigned to the position of the element to be inserted. Because were saved at the beginning has to be inserted into the elements, so just to be inserted element value is assigned to its previous element can be. Because while loop InsertIndex decrement operation is performed, so that the front element index should insertIndex + 1. If the element to be inserted is greater than the previous element, while it will not enter the circulation, such insertIndex + 1 position after their location is still, so that after the assignment is not changed, and so the latter operation.

4. Shell sort

The traditional insertion sort algorithm there are some problems in certain scenarios, such as [2,3,4,5,1] such an array, when we insert them time to sort of find you want to insert the number is 1, However, if the insert 1 to the front, to go through four steps, respectively, after 5,4,3,2 shift. So to conclude: if the smaller number is the number we need to insert that efficiency will be relatively low. Given the drawbacks of this scenario, Hill sorting born, it is the insertion sort of a more efficient version.
Take a look at the sort of notion Hill:
Hill sorting (Shell's Sort) insertion sort is also known as a "zoom increment sort" (Diminishing Increment Sort), it is directly into the Ranking algorithm more efficient improved version. Hill sorting non-stationary sorting algorithm. The method proposed in 1959 due to DLShell named.
Shell sort is the subject of pressing the recording packet in increments, the use of direct insertion sort each sorting algorithm; With increment is gradually reduced, more and more keywords each comprising, when reduced to an increment, the entire file is divided into just one set, the algorithm will terminate.

Demo:
Here Insert Picture Description
Animation If you do not understand, I'm here to paste a few still pictures:
Here Insert Picture Description
code implementation:

@Test
public void ShellSort() {
    int[] arr = { 3, 44, 38, 5, 47, 15, 36, 26, 27, 2, 46, 4, 19, 50, 48 };
    for (int gap = arr.length / 2; gap > 0; gap /= 2) {
        // 对数组元素进行分组
        for (int i = gap; i < arr.length; i++) {
            // 遍历各组中的元素
            for (int j = i - gap; j >= 0; j -= gap) {
                // 交换元素
                if (arr[j] > arr[j + gap]) {
                    int temp = arr[j];
                    arr[j] = arr[j + gap];
                    arr[j + gap] = temp;
                }
            }
        }
    }

    System.out.println(Arrays.toString(arr));
}

operation result:

[2, 3, 4, 5, 15, 19, 26, 27, 36, 38, 44, 46, 47, 48, 50]

Then in the block above, the length of the array 15, so in the first round, the array is divided into 15/2 = 7 groups, and each group the separate elements to traverse. In fact, that is the spacing between the elements in the first round the number of group elements in the interval between group 7 are so divided. Then it may be made to the elements of each group and then making the exchange, the next and so on.

Guess you like

Origin www.cnblogs.com/blizzawang/p/11411533.html