Algorithm: eight commonly used sorting algorithms and code implementation

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

public void insertSort(int[] a){
        int length=a.length;//Array length, which is extracted to improve speed.
        int insertNum;//Number to insert
        for(int i=1;i<length;i++){//Number of inserts
            insertNum=a[i];//Number to insert
            int j=i-1;//Number of ordered sequence elements
            while(j>=0&&a[j]>insertNum){//The sequence circulates from back to front, moving the number greater than insertNum backward one grid
                a[j+1]=a[j];//Element moves one grid
                j--;
            }
            a[j+1]=insertNum;//Place the number you want to insert in the location you want to insert.
        }
    }

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 fractions
                for (int i = x + d; i < a.length; i += d) {//Elements in a group, starting with the second number
                    int j = i - d;//j is the last digit of an ordered sequence
                    int temp = a[i];//Elements to insert
                    for (; j >= 0 && temp < a[j]; j -= d) {//Go back and forth.
                        a[j + d] = a[j];//Move d bits backward
                    }
                    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.

 public void selectSort(int[] a) {
        int length = a.length;
        for (int i = 0; i < length; i++) {//Cycle times
            int key = a[i];
            int position=i;
            for (int j = i + 1; j < length; j++) {//Select the minimum value and location
                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.
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.

public  void heapSort(int[] a){
        System.out.println("Start sort");
        int arrayLength=a.length;
        //Cyclic construction  
        for(int i=0;i<arrayLength-1;i++){
            //Build heap  

            buildMaxHeap(a,arrayLength-1-i);
            //Swap top and last elements  
            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;
    }
    //Building a large top heap for data array from 0 to lastIndex  
    private void buildMaxHeap(int[] data, int lastIndex) {
        // TODO Auto-generated method stub  
        //Starting from the parent of the node (last node) at lastIndex  
        for(int i=(lastIndex-1)/2;i>=0;i--){
            //k save the node being judged  
            int k=i;
            //If a child of the current k-node exists  
            while(k*2+1<=lastIndex){
                //Index of the left child of the k node  
                int biggerIndex=2*k+1;
                //If biggerIndex is smaller than lastIndex, the right child node of k node represented by biggerIndex+1 exists  
                if(biggerIndex<lastIndex){
                    //If the value of the right child node is large  
                    if(data[biggerIndex]<data[biggerIndex+1]){
                        //biggerIndex always records the index of the larger child node  
                        biggerIndex++;
                    }
                }
                //If the value of a k-node is less than the value of its larger child nodes  
                if(data[k]<data[biggerIndex]){
                    //Swap them  
                    swap(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 completed.

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 sorting

Ask for the fastest time.
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.

public static void quickSort(int[] numbers, int start, int end) {   
    if (start < end) {   
        int base = numbers[start]; // Selected datum (first value as datum)   
        int temp; // Record 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.

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 of 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.

public void sort(int[] array) {
        //First, determine the number of times to sort;     
        int max = array[0];
        for (int i = 1; i < array.length; i++) {
            if (array[i] > max) {
                max = array[i];
            }
        }
        int time = 0;
        //Number of judgment digits;     
        while (max > 0) {
            max /= 10;
            time++;
        }
        //Establish 10 queues;     
        List<ArrayList> queue = new ArrayList<ArrayList>();
        for (int i = 0; i < 10; i++) {
            ArrayList<Integer> queue1 = new ArrayList<Integer>();
            queue.add(queue1);
        }
        //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+1 digit of the number;   
                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++;
                }
            }
        }
    }
Published 130 original articles, won praise 31, visited 40000+
Private letter follow

Tags: less REST

Posted on Sun, 08 Mar 2020 05:39:27 -0400 by dkim777