If young people want to learn algorithms, they will use 8 sorting algorithms and code implementation commonly used in Java

Time:2021-6-23

In today’s Internet environment, technical personnel job interview, data structure and algorithm knowledge investigation has become one of the most important points of the interviewer. Some algorithms are sure to be used in our work and interview. Today, let’s talk about eight commonly used sorting algorithms and code implementation.

If young people want to learn algorithms, they will use 8 sorting algorithms and code implementation commonly used in Java

1. Direct insertion sort

We often encounter such a sort of sorting problem: inserting new data into the already arranged data column.

  1. Sort the first number and the second number to form an ordered sequence
  2. Insert the third number to form a new ordered sequence.
  3. Repeat the second step for the fourth number, the fifth number… Until the last number.

If young people want to learn algorithms, they will use 8 sorting algorithms and code implementation commonly used in Java

How to write code:

  1. First, set the number of insertion, that is, the number of cycles, for (int i = 1; i<length; I + +), the number of 1 does not need to be inserted.
  2. Set the number of inserts and the number of digits to get the last number in the sequence. Insertnum and j = I-1.
  3. Loop forward from the last number. If the insert number is less than the current number, move the current number backward by one bit.
  4. Put the current number in an empty position, that is, j + 1.
    The code implementation is as follows:

“The latest video tutorial and learning route of basic Java in 2020!”

public void insertSort(int[] a){
        int length=a.length;// The length of the array is extracted to improve the speed.
        int insertNum;// Number to insert
        for(int i=1; i<length; I + +) {// the number of inserts
            insertNum=a[i];// Number to insert
            int j=i-1;// Number of sorted sequence elements
            When (J > = 0 & & A [J] > insertnum) {// the sequence loops from back to front, moving the number greater than insertnum one lattice backward
                a[j+1]=a[j];// Elements move one space
                j--;
            }
            a[j+1]=insertNum;// Place the number you want to insert in the position you want to insert.
        }
    }

2. Hill sort

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

  1. Set the number of numbers to N, take the odd number k = n / 2, and divide the books with subscript difference K into a group to form an ordered sequence.
  2. Then take k = K / 2, divide the books whose subscript difference is K into a group to form an ordered sequence.
  3. Repeat the second step until k = 1 performs a simple insert sort.

If young people want to learn algorithms, they will use 8 sorting algorithms and code implementation commonly used in Java

How to write code:

  • First, the number of groups is determined.
  • Then insert and sort the elements in the group.
  • Then repeat steps 1 and 2 with 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 groups
                for (int i = x + d;  i < a.length;  I + = D) {// the element in the group, starting with the second number
                    int j = i - d;// J is the number of digits of the last digit of an ordered sequence
                    int temp = a[i];// Element to insert
                    for (;  j >= 0 && temp < a[j];  J - = D) {// traverse from back to front.
                        a[j + d] = a[j];// Move D bit backward
                    }
                    a[j + d] = temp;
                }
            }
        }
    }

3. Simple selection and sorting

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

(if every comparison is exchanged, it is the exchange sort; If you exchange after comparing one cycle at a time, you simply select sort.)

  1. Traverse the entire sequence, putting the smallest number first.
  2. Traverse the rest of the sequence, putting the smallest number first.
  3. Repeat the second step until there is only one number left.

If young people want to learn algorithms, they will use 8 sorting algorithms and code implementation commonly used in Java

How to write code:

  1. First determine the number of cycles and remember the current number and current position.
  2. Compare all the numbers after the current position with the current number, assign the decimal value to the key, and remember the position of the decimal.
  3. After the comparison, the minimum value is exchanged with the value of the first number.
  4. Repeat steps 2 and 3.
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 value and position
                if (a[j] < key) {
                    key = a[j];
                    position = j;
                }
            }
            a[position]=a[i];// change of position
            a[i]=key;
        }
    }

4. Heap sort

Optimization of simple selection sorting.

  1. The sequence was constructed into a large top pile.
  2. Swap the root node with the last node, and then disconnect the last node.
  3. Repeat steps 1 and 2 until all nodes are disconnected.

If young people want to learn algorithms, they will use 8 sorting algorithms and code implementation commonly used in Java

The code implementation is as follows:

public  void heapSort(int[] a){
        System. Out. Println ("start sorting");
        int arrayLength=a.length;
        //Recycle reactor construction  
        for(int i=0;i<arrayLength-1;i++){
            //Build a pile  

            buildMaxHeap(a,arrayLength-1-i);
            //Swap the top of the heap 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;
    }
    //Build big top heap for data array from 0 to lastindex  
    private void buildMaxHeap(int[] data, int lastIndex) {
        // TODO Auto-generated method stub  
        //Start with the parent node of the node at lastindex (the last node)  
        for(int i=(lastIndex-1)/2;i>=0;i--){
            //K saves the node being judged  
            int k=i;
            //If the child node of the current K node exists  
            while(k*2+1<=lastIndex){
                //Index of the left child of K node  
                int biggerIndex=2*k+1;
                //If biggerindex is less than lastindex, the right child of K node represented by biggerindex + 1 exists  
                if(biggerIndex<lastIndex){
                    //If the value of the right child node is larger  
                    if(data[biggerIndex]<data[biggerIndex+1]){
                        //Biggerindex always records the index of the larger child node  
                        biggerIndex++;
                    }
                }
                //If the value of K node is less than that of its larger child node  
                if(data[k]<data[biggerIndex]){
                    //Exchange them  
                    swap(data,k,biggerIndex);
                    //The biggerindex is given to K to start the next cycle of the while loop, and the value of K node is re guaranteed to be greater than that of its left and right child nodes  
                    k=biggerIndex;
                }else{
                    break;
                }
            }
        }
    }

5. Bubble sort

Generally not.

  1. All elements in the sequence are compared in pairs, with the largest at the end.
  2. All elements in the remaining sequence are compared in pairs, with the largest at the end.
  3. Repeat the second step until there is only one number left.

If young people want to learn algorithms, they will use 8 sorting algorithms and code implementation commonly used in Java

How to write code:

  1. Set the number of cycles.
  2. Set the number of digits to start and end the comparison.
  3. Compare each other and put the smallest one in front.
  4. Repeat steps 2 and 3 until the number of cycles is complete.

The code implementation is as follows:

public void bubbleSort(int[] a){
        int length=a.length;
        int temp;
        for(int i=0;i<a.length;i++){
            for(int j=0;j<a.length-i-1;j++){
                if(a[j]>a[j+1]){
                    temp=a[j];
                    a[j]=a[j+1];
                    a[j+1]=temp;
                }
            }
        }
    }

6. Quick sort

The fastest time is required.

  1. Select the first number as P, the number less than P on the left and the number greater than P on the right.
  2. Recursively, the numbers on the left and right of P are carried out according to the first step until they cannot be recursed.

If young people want to learn algorithms, they will use 8 sorting algorithms and code implementation commonly used in Java

The code implementation is as follows:

public static void quickSort(int[] numbers, int start, int end) {   
    if (start < end) {   
        int base = numbers[start]; //  Selected reference value (first value as reference value)   
        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. It can be used when there is little memory and parallel computing.

  1. Select two adjacent numbers to form an ordered sequence.
  2. Two adjacent ordered sequences are selected to form an ordered sequence.
  3. Repeat the second step until all of them form an ordered sequence.

If young people want to learn algorithms, they will use 8 sorting algorithms and code implementation commonly used in Java

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. Radix sort

It is used for sorting large numbers and long numbers.

  1. Take out the single digits of all numbers and sort them according to the single digits to form a sequence.
  2. Take out the ten digits of all the new numbers and sort them according to the ten digits to form a sequence.

If young people want to learn algorithms, they will use 8 sorting algorithms and code implementation commonly used in Java

The code implementation is as follows:

public void sort(int[] array) {
        //Firstly, the number of times of sorting is determined;     
        int max = array[0];
        for (int i = 1; i < array.length; i++) {
            if (array[i] > max) {
                max = array[i];
            }
        }
        int time = 0;
        //Judgment digit;     
        while (max > 0) {
            max /= 10;
            time++;
        }
        //10 queues were established;     
        List<ArrayList> queue = new ArrayList<ArrayList>();
        for (int i = 0; i < 10; i++) {
            ArrayList<Integer> queue1 = new ArrayList<Integer>();
            queue.add(queue1);
        }
        //Distribution and collection of time;     
        for (int i = 0; i < time; i++) {
            //Allocate array elements;     
            for (int j = 0; j < array.length; j++) {
                //The time + 1 digit of the number is obtained;   
                int x = array[j] % (int) Math.pow(10, i + 1) / (int) Math.pow(10, i);
                ArrayList<Integer> 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<Integer> queue3 = queue.get(k);
                    array[count] = queue3.get(0);
                    queue3.remove(0);
                    count++;
                }
            }
        }
    }

Link address:https://blog.csdn.net/qq_50524970/article/details/110531344