# Shaky foundation: remember eight sorting algorithms and code implementation commonly used in Java

## 1. Direct insertion sorting

Often encountered such a sort of problem: insert new data into the already arranged data column.

• Sort the first number and the second number to form an ordered sequence

• Insert the third number to form a new ordered sequence.

• For the fourth number, the fifth number Repeat step 2 until the last number. How to write code:

• First, set the insertion times, i.e. the number of cycles, for (int i = 1; I < length; I + +). The insertion of one number is not needed. < span>

• Set the number of inserts and the number of digits to get the last number of the ordered sequence. insertNum and j=i-1.

• Cycle forward from the last number. If the inserted number is less than the current number, move the current number one bit backward.

• Place the current number in an empty position, j+1.

The code implementation is as follows:

`public void insertSort(int[] a){        int length=a.length;//Array length, which is extracted to improve speed. Int insertNum; / / the number to insert for(int i = 1; I < length; I + +) {/ / the number of insertNum=a[i]; / / the number to insert int j=i-1; / / the number of sequenced sequence elements while (J > = 0 & & a [J] > insertNum) {/ / the sequence cycles from the back to the front, and the number greater than insertNum is reversed Move a cell a[j+1]=a[j]; / / move an element a cell J --;} a[j+1]=insertNum; / / put the number to be inserted in the position to be inserted.         }    }`

## 2. Hill sorting

For the direct insertion sorting problem, when the amount of data is huge.

• Set the number of numbers as N, take the odd number k=n/2, and divide the number whose subscript difference is K into a group to form an ordered sequence.

• Then take k=k/2, and divide the books whose subscript difference is K into a group to form an ordered sequence.

• Repeat the second step until k=1 performs a simple insert sort. How to write code:

• First determine the number of components.

• The elements in the group are then inserted and sorted.

• Then repeat steps 1 and 2 for length/2 until length=0.

The code implementation is as follows:

`public  void sheelSort(int[] a){        int d  = a.length;        while (d!=0) {            d=d/2;            for (int x = 0; x < d; x++) {//Number of components for (int i = x + d; I < a.len gt h; I + = d) {/ / the element in the group, starting from the second number. Int j = I - d;//j is the digit number of the last digit of the ordered sequence. Int temp = a[i]; / / the element to be inserted For (; J > = 0 & & Temp < a[j]; J - = d) {/ / traverse from back to front. a[j + d] = a[j]; / / move d bit} a[j + d] = temp;}}}}}}}`

## 3. Simple selection and sorting

It is often used to get the maximum and minimum numbers in a sequence.

(if each comparison is exchanged, it is exchange sorting; if each comparison is exchanged after one cycle, it is simple selection sorting. )

• Traverse the entire sequence, putting the minimum number first.

• Traverse the rest of the sequence, putting the minimum number first.

• Repeat the second step until there is only one number left. How to write code:

• First determine the number of cycles and remember the current number and current position.

• Compare all the numbers after the current position with the current number, assign the decimal to the key, and remember the decimal position.

• After the comparison, the minimum value is exchanged with the value of the first number.

• Repeat steps 2 and 3.

The code implementation is as follows:

`3. Simple selection sorting is often used to get the maximum and minimum number in the sequence. (if each comparison is exchanged, it is exchange sorting; if each comparison is exchanged after one cycle, it is simple selection sorting. )Traverse the entire sequence, putting the minimum number first. Traverse the rest of the sequence, putting the minimum number first. Repeat the second step until there is only one number left. How to write a code: first determine the number of cycles, and remember the current number and location. Compare all the numbers after the current position with the current number, assign the decimal to the key, and remember the decimal position. After the comparison, the minimum value is exchanged with the value of the first number. Repeat steps 2 and 3. The code implementation is as follows: public void selectSort(int [] a) {int length = a.length; for (int i = 0; I < length; I + +) {/ / number of cycles int key = a[i]; int position=i; for (int j = I + 1; J < length; j + +) {/ / select the minimum If (a[j] < key) {key = a[j]; position = J;}}} a[position]=a[i]; / / exchange position a[i]=key;}}}}`

## 4. heap sort

Optimization of simple selection sorting.

• Build the sequence into a large top heap.

• Swap the root node with the last node, and then disconnect the last node.

• Repeat steps 1 and 2 until all nodes are disconnected. The code implementation is as follows:

`public  void heapSort(int[] a){        System.out.println("Start sort");        int arrayLength=a.length;        //Loop build for(int i = 0; I < arraylength-1; I + +) {/ / build maxheap (a, arraylength-1-i); / / swap the top and the last element swap(a,0,arrayLength-1-i); System.out.println(Arrays.toString(a)) }} private void swap(int [] data, int i, int j) {/ / TODO auto generated method stub int tmp=data[i]; data[i]=data[j]; data[j]=tmp;} / / private void buildMaxHeap(int [] data, int last) for data array from 0 to lastIndex Index) {/ / TODO auto generated method stub / / for(int i = (lastIndex-1) / 2; I > = 0; I --) {/ / K preserves the node being judged int k=i; / / if the child of the current K node The node has while (k * 2 + 1 < = lastIndex) {/ / the index of the left child node of the K node int biggerIndex=2*k+1; / / if the biggerIndex is smaller than lastIndex, the right child node of the K node represented by biggerIndex+1 has if( biggerIndex < lastIndex) {/ / if the value of the right child node is larger (data [biggerIndex] < data [biggerIndex+1]) {/ / biggerIndex always records the index of the larger child node. biggerIndex + + }} / / if the value of the K node is less than the value of its larger child node (data [k] < data [biggerIndex]) {/ / swap them (data, K, biggerIndex) / / give the biggerIndex to K, start the next cycle of the while cycle, and make sure that the value of the K node is greater than the value of its left and right child nodes. k=biggerIndex;} else {break;}    }        }    }`

## 5. Bubble sorting

Generally not.

• Compare all elements of the sequence in pairs, with the largest one at the end.

• Compare all the elements in the remaining sequence in pairs, and put the largest one at the end.

• Repeat the second step until there is only one number left. How to write code:

• Set the number of cycles.

• Set the number of digits to start and end the comparison.

• Compare the two and put the smallest one in front.

• Repeat steps 2 and 3 until the number of cycles is complete.

The code implementation is as follows:

## 6. Quick sorting

• Select the first number as p, and put the number less than p on the left, and the number greater than p on the right.

• Recursively follow the first step for the left and right numbers of p until recursion is not possible. The code implementation is as follows:

`public static void quickSort(int[] numbers, int start, int end) {       if (start < end) {           int base = numbers[start]; //Int temp; / / record the temporary intermediate value int i = start, j = end; do {while ((numbers [i] < base) & (I < end)) I + +; while ((numbers[j] > base) && (j > start))                   j--;               if (i <= j) {                   temp = numbers[i];                   numbers[i] = numbers[j];                   numbers[j] = temp;                    i++;                   j--;               }           } while (i <= j);           if (start < j)               quickSort(numbers, start, j);           if (end > i)               quickSort(numbers, i, end);       }   }`

## 7. Merge and sort

The speed is second only to fast row, which can be used when there is less memory and parallel computing can be carried out.

• Select two adjacent numbers to form an ordered sequence.

• Two adjacent ordered sequences are selected to form an ordered sequence.

• Repeat the second step until it all forms an ordered sequence. The code implementation is as follows:

`public static void mergeSort(int[] numbers, int left, int right) {       int t = 1;//Number of elements in each group int size = right - left + 1; while (T < size) {int s = t; / / number of elements in each group in this cycle T = 2 * s; int i = left; while (I + (T - 1) < size) {merge (numbers) , i, i + (s - 1), i + (t - 1));               i += t;           }           if (i + (s - 1) < right)               merge(numbers, i, i + (s - 1), right);       }   }   private static void merge(int[] data, int p, int q, int r) {       int[ ] B = new int[data.length];       int s = p;       int t = q + 1;       int k = p;       while (s <= q && t <= r) {           if (data[s] <= data[t]) {               B[k] = data[s];               s++;           } else {                B[k] = data[t];               t++;           }           k++;       }       if (s == q + 1)           B[k++] = data[t++];       else          B[k++] = data[s++];       for (int i = p; i <= r; i++)           data[i] = B[i];}`

## 8. Cardinality sorting

Used for sorting a large number or a long number.

• Take out the single digits of all numbers and sort them according to the single digits to form a sequence.

• Take out the tens of all the new numbers and sort them according to the tens to form a sequence. The code implementation is as follows:

`public void sort(int[] array) {        //First, determine the number of sorting passes; int max = array; for (int i = 1; I < array.length; I + +) {if (array[i] > max) {max = array[i];}} int time = 0; / / determine the number of digits While (max > 0) {max / = 10; time + +;} / / create 10 queues; List queue = new ArrayList(); for (int i = 0; I < 10; I + +) {ArrayList queue1 = new ArrayList() queue.add(queue1);} / / perform time allocation and collection; for (int i = 0; I < time; I + +) {/ / allocate array elements; for (int j = 0; J < array.length; j + +) {/ / get the time of the number +1 digit; int x = array[j]% (int) Math.pow(10, I + 1) / (int) Math.pow(10, i); ArrayList Queue2 = queue.get(x); queue2.add(array[j]); queue.set(x, queue2);} Int count = 0; / / element counter; / / collect queue elements; for (int k = 0; K < 10; K + +) {while (queue.get(k).size() > 0) {ArrayList queue3 = queue.get(k)  array[count] = queue3.get(0);                    queue3.remove(0);                    count++;                }            }        }    }`

If you think the article is good, please pay attention to it. More content will be presented one after another.

Finally, share an interview treasure book "Java core knowledge point arrangement. pdf", covering JVM, lock, high concurrency, reflection, Spring principle, microservice, Zookeeper, database, data structure, etc. Join my personal fan group (Java architecture technology stack: 644872653) to get free collection.

Tags: Java less REST jvm

Posted on Sat, 01 Feb 2020 02:34:50 -0500 by romeo