Sorting algorithm summary-Java implementation

table of Contents

1. Introduction to sorting algorithm

Two, direct insertion sort

Three, half insertion sort

Four, direct selection sort

Five, bubble sort

Six, Hill sort

Seven, quick sort

Eight, heap sort

Nine, merge sort


 

1. Introduction to sorting algorithm

Sorting is to arrange the data in an orderly manner according to certain rules, generally divided into descending order and ascending order.

There are many algorithms for sorting. We need to consider the following factors when testing these algorithms.

  • Time complexity: a measure of the time taken from the initial state of the sequence to the transformation and shifting of the sorting algorithm to the final state of the sorted result.
  • Space complexity: the space overhead spent from the initial state of the sequence through the process of sorting shift transformation to the final state
  • Stability: In the record sequence to be sorted, there are multiple records with the same key. If the relative order of these records remains unchanged after sorting, the algorithm is said to be stable, otherwise it is unstable
    • For example, 3,2_a,2_b,1after the algorithm is sorted in descending order 1,2_a,2_b,3, the algorithm is said to be stable; if it is obtained 1,2_b,2_a,3, the algorithm is said to be unstable.

 

Common sorting algorithms are as follows:

algorithm time complexity Space complexity stability
Direct insertion sort O (n ^ 2) O (1)
Half Insertion Sort O (n ^ 2) O (1)
Direct selection sort O (n ^ 2) O (1)
Bubble Sort O (n ^ 2) O (1)
Hill sort O (nlog_2n) \ sim O (n ^ 2) O (1) ×
Quick sort O (nlog_2n) O(log_2n) ×
Heap sort O (nlog_2n) O (1) ×
Merge sort O (nlog_2n) O (n)

Next, we will introduce them one by one (will continue to be updated in the future)

 

Two, direct insertion sort

Ideas:

The idea of ​​direct insertion sort is that when the i-th element is inserted, the previous i-1 elements are already sorted.

At this time, you only need to find the inserted position to insert the i-th element. At this time, the array is arranged in an orderly manner.

 

achieve:

    //直接插入排序
    public static int[] InsertSort(int[] arr){
        for (int i = 0; i < arr.length; i++) {
            for (int j = 0; j < i; j++) {
                if(arr[i]<arr[j]){
                    swap(arr,i,j);
                }
            }
        }
        return arr;
    }

 

result:

The time complexity of direct insertion sort is O (n ^ 2), the space complexity is O (1), it is a stable algorithm

 

Three, half insertion sort

Ideas:

The idea of ​​half insertion sort is similar to that of direct insertion sort, but half insertion sort uses a half search when looking for the position where the i-th element is inserted.

The prerequisite for using binary search is that the array is in order, which happens to be a feature of insertion sort. The first i-1 elements are already in order.

 

achieve:

    //折半插入排序
    public static int[] BinaryInsertSort(int[] arr){
        for (int i = 1; i < arr.length; i++) {
            int cur=arr[i];
            int low=0;
            int high=i-1;
            while(low<=high){//查找要插入的位置,并将下标放到low中
                int mid=(low+high)/2;
                if(arr[mid]>cur) {
                    high=mid-1;
                }else {
                    low=mid+1;
                }
            }
            for (int j = i; j > low ; j--) {
                arr[j]=arr[j-1];
            }
            arr[low]=cur;
        }
        return arr;
    }

 

result:

The time complexity of the binary insertion sort is O (n ^ 2), the space complexity is O (1), and it is a stable algorithm

 

Four, direct selection sort

Ideas:

The idea of ​​direct selection and sorting is simpler, that is, the smallest (larger) number is selected in the first round and placed in the first position.

In the next round, the previously selected elements are not considered, and the largest of the remaining elements is selected and placed in the second position, and so on, until the number of remaining elements is 1, then the array must be in order.

 

achieve:

    //直接选择排序
    public static int[] SelectSort(int[] arr){
        for (int i = 0; i < arr.length; i++) {
            for (int j = i; j < arr.length; j++) {
                if(arr[i]>arr[j]){
                    swap(arr,i,j);
                }
            }
        }
        return arr;
    }

 

result:

The time complexity of the binary insertion sort is O (n ^ 2), the space complexity is O (1), and it is a stable algorithm

 

Five, bubble sort

Ideas:

The idea of ​​bubbling sorting is similar to spitting bubbles in the water, light elements will automatically float to the surface, and heavy elements will sink to the bottom.

We start with the first element and compare it with the size of the next element. If the value of the former is greater, then swap the positions of the two elements and let the heavy element sink slowly.

Then compare the second and the third. If the previous element is large, swap positions, and the heavy element will sink until you compare the size of the last two elements and sink the heavy one, so that the largest element can be guaranteed in one round. Sink to the end of the array,

Then in the next loop, you only need to bubble the first n-1 elements. Each round can determine the final position of an element, and the array will become ordered after n-1 rounds.

 

achieve:

    //冒泡排序
    public static int[] BubbleSort(int[] arr){
        for (int i = 0; i < arr.length-1; i++) {
            for (int j = 0; j < arr.length-i-1; j++) {
                if(arr[j]>arr[j+1]){
                    swap(arr,j,j+1);
                }
            }
        }
        return arr;
    }

 

result:

The time complexity of bubble sort is O (n ^ 2), the space complexity is O (1), it is a stable algorithm

 

Six, Hill sort

Ideas:

Hill sort is an improved version of insertion sort. The basic idea is to divide the array into several small sub-arrays for insertion sort.

The grouping strategy is to take the integer gap, group the elements whose subscripts are separated by the gap into a group, and insert and sort the elements of the group.

Then reduce the value of gap next time until gap takes 1, and the entire array becomes ordered after insert sorting is used.

 

achieve:

    //希尔排序
    public static int[] ShellSort(int[] arr){
        int gap=arr.length;
        do{
            gap=gap/3+1;//希尔初始设置的减量为gap=gap/2;
            System.out.println("----------------");
            System.out.println(gap);
            for (int i = 0; i < gap; i++) {//对每个子数组进行插入排序
                System.out.println("------");
                for (int j = i+gap; j < arr.length; j+=gap) {
                    System.out.println("j:"+j);
                    int k=j-gap;
                    while(k>=0&&arr[k]>arr[k+gap]){
                        swap(arr,k,k+gap);
                        k-=gap;
                    }
                    print(arr);
                }
            }
        }while(gap>1);
        return arr;
    }

 

result:

The time complexity of the direct insertion sort is O (nlog_2n) \ sim O (n ^ 2), the space complexity is O (1), it is an unstable algorithm

 

Seven, quick sort

Ideas:

The idea of ​​quick sort is to first select the first element of the array as a benchmark, and divide the array into two parts.

The elements on the left are smaller than the reference, and the elements on the right are larger than the reference, so that the location of the reference element is its final position, and then recursively call the left and right arrays to sort.

 

achieve:

    //快速排序
    public static int[] QuickSort(int[] arr,int low,int high){
        if(low<high){
            int curpos=Partition(arr,low,high);
            QuickSort(arr,low,curpos-1);
            QuickSort(arr,curpos+1,high);
        }
        return arr;
    }

    public static int Partition(int[] arr,int low,int high){
        int curPos=low;
        int curVal=arr[low];
        for (int i = low+1; i <= high; i++) {
            if(arr[i]<curVal){
                curPos++;//循环结束之后可以找到当前元素在数组中的下标
                if(curPos!=i){//将处于右边小于当前元素的数交换到左边
                    swap(arr,curPos,i);
                }
            }
            print(arr);
        }
        arr[low]=arr[curPos];//将当前元素放置到应位置
        arr[curPos]=curVal;
        return curPos;
    }

 

result:

The time complexity of the direct insertion sort is O (nlog_2n), the space complexity is O(log_2n), it is an unstable algorithm

 

Eight, heap sort

Ideas:

Heap sorting uses the characteristics of the heap, that is, the value of the parent node is always greater than the value of the child node, so the root node stores the largest value in the entire array. So how to build such a heap structure?

First, we build a binary tree structure according to the subscript of the array, and then start processing from the largest non-leaf node, and compare it with the larger one of the child nodes. If the child node has a greater value than its value, then swap The value of the two nodes floats the big element up and the small element down,

Because the structure of the tree is changed at this time, and the small element sinks, there is no guarantee that the child nodes of the sinking element are smaller than the node, so the child nodes must also be adjusted at the same time.

Until it sinks to a certain node, its child nodes are all smaller than the element.

All non-leaf nodes are adjusted to the root node, so that the entire binary tree is adjusted into a heap, and the root node is the largest element.

The next step is to sort the array. We first swap the first position element of the array with the last position element of the array, so that the largest element is placed at the end of the array and its position is determined.

Then adjust the first n-1 elements to re-establish a new maximum pile, select the second largest element at the root node, and then change the position of the second to last, and the position of the second to last element is also determined.

By analogy, you can finally get an ordered array.

 

achieve:

    //堆排序
    public static int[] heapSort(int[] arr) {
        for (int i = arr.length/2-1; i >= 0; i--) {
            adjustHeap(arr,i,arr.length);
        }

        for (int j = arr.length-1; j >0 ; j--) {
            swap(arr,0,j);
            adjustHeap(arr,0,j);
        }
        return arr;
    }

    //调整堆:arr 待组堆, i 起始结点, length 堆的长度
    public static void adjustHeap(int[] arr, int i, int length) {
        int temp=arr[i];
        for (int k = 2*i+1; k < length; k=2*k+1) {
            if(k+1<length && arr[k]<arr[k+1]){
                k++;
            }
            if(arr[k]>temp){
                swap(arr,i,k);
                i=k;//对调换之后的节点进行调整
            }else{
                break;
            }
        }
    }

 

result:

The time complexity of the direct insertion sort is O (nlog_2n), the space complexity is O (1), it is an unstable algorithm

 

Nine, merge sort

Ideas:

The idea of ​​merging and sorting is to divide the array into two continuously to get two arrays until there is only one element in the array.

Then reverse the merge. When merging, define two pointers, which point to the initial positions of the two arrays at the same time, and compare the sizes of the elements pointed to by the pointers.

The element with the smaller value is put into the corresponding position in the result array, and then the pointer is moved back until the elements of the two arrays are put into the corresponding position in the result array.

 

achieve:

    //归并排序
    public static int[] MergeSort(int[] arr){
        int[] res=new int[arr.length];
        mergeSort(arr,res,0,arr.length-1);
        return arr;
    }

    public static void mergeSort(int[] arr,int[] res,int low,int high){
        if(low>=high){
            return;
        }else{
            int mid=(low+high)/2;
            mergeSort(arr,res,low,mid);
            mergeSort(arr,res,mid+1,high);
            merge(arr,res,low,mid,high);
        }
    }

    public static void merge(int[] arr,int[] res,int low,int mid,int high){
        for (int i = low; i <= high; i++) {
            res[i]=arr[i];
        }
        int i=low;
        int j=mid+1;
        int k=low;
        while(i<=mid && j<=high) {
            if(res[i]>res[j]){
                arr[k++]=res[j++];
            }else{
                arr[k++]=res[i++];
            }
        }
        while(i<=mid){
            arr[k++]=res[i++];
        }
        while(j<=high){
            arr[k++]=res[j++];
        }
    }

 

result:

The time complexity of direct insertion sort is O (nlog_2n), the space complexity is O (n), it is a stable algorithm

 

Guess you like

Origin blog.csdn.net/weixin_39478524/article/details/115129299