Sorting Algorithm summary (bubble sort, select sort, direct insertion sort, Hill shell sort, quick sort, merge sort, radix sort)

Fourth, the sort (Sort Algorithm)

1, the concept of

The concept of sorting: Sort process is a set of data arranged in the order specified.

Sorting can be divided into external and internal sorting sort all the data inside the sort processing is loaded into the internal memory are sorted.

If the data is too large to load into memory all, need to be sorted by means of an external storage.

1.1, internal sorting

  • Insertion Sort

Direct insertion sort, Shell sort

  • Selection Sort

Simple selection sort, heap sort

  • Sort exchange

Bubble sort, quick sort

  • Merge sort
  • Radix Sort

1.2 external sorting

2, sorting algorithm

2.1 Bubble Sort

Concept: bubble sort is the sort of exchange, its basic idea is: according to some ordering rules, any two adjacent key element, if the exchange is in reverse order, until there are no records in reverse order.

  • Ordinary bubble algorithm

    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]) {
                        swap(arr, j, j + 1);
                    }
                }
                System.out.println(Arrays.toString(arr));
            }
    
  • Sorting algorithm optimization

    There is a case, when there is no data exchange, i.e. the description of this sequence has been ordered, i.e. no need to determine the data back, we need to optimize the code, i.e., when the sequence has been ordered, the data is no longer on the back of judgment.

     boolean flag = true;
            for (int i = 0; i < arr.length - 1&&flag; i++) {
                flag=false;
                for (int j = 0; j < arr.length - 1 - i; j++) {
                    if (arr[j] > arr[j + 1]) {
                        swap(arr, j, j + 1);
                        flag = true;
                    }
                }
                System.out.println(Arrays.toString(arr));
            }
    

2.2 simple selection sort

Concept: that is, through a comparison between ni Keywords from ni + 1 (including its own) the smallest key selected recording recording, and the i-th recording and exchange.

for (int i = 0; i < arr.length - 1; i++) {
            int minSize = i;
            int min = arr[minSize];
            for (int j = i + 1; j <= arr.length - 1; j++) {
                if(min>arr[j]){
                    minSize=j;
                    min=arr[j];
                }
            }
            if(i!=minSize){
                arr[minSize]=arr[i];
                arr[i]=min;

            }
        }

Direct insertion sort 2.3

Concept: The n-th ordered elements to be see as an unordered and an ordered list table , order table contains only one element at the beginning of unordered list contains the n-1 element from each sorting process disordered remove the first element in the table, it is successively compared with the sorting code ordered list of sort key element, it is inserted into the appropriate location in the ordered list, in order to become the new table.

int insertScrpt=0;//要插入的位置
        int insertValue=0;//插入的值
        for(int i=1;i<=arr.length-1;i++){
            insertScrpt=i-1;
            insertValue=arr[i];
            while (insertScrpt>=0&&insertValue<arr[insertScrpt]){
                arr[insertScrpt+1]=arr[insertScrpt];//向后移
                insertScrpt--;
            }
            if(insertScrpt+1!=i){
                arr[insertScrpt+1]=insertValue;
            }
        }

2.4 Shell sort

Concept: Shell sort is the subject of pressing the recording packet in increments, the use of direct insertion sort each sorting algorithm; with decreasing increments, each keyword contained more, the increment is reduced when 1, the entire file is divided into a set of pinch algorithm terminates.

  • Exchange (the time complexity is about 17S)

    int temp = 0;
            for (int increment = arr.length / 2; increment > 0; increment = increment / 2) {
                for (int i = increment; i < arr.length; i++) {
                    for (int j = i - increment; j >= 0; j -= increment) {
                        if (arr[j] > arr[j + increment]) {
                            temp = arr[j];
                            arr[j] = arr[j + increment];
                            arr[j + increment] = temp;
                        }
                    }
                }
                System.out.println(Arrays.toString(arr));
            }
    
  • Shift method (time complexity is about 1s)

    for (int increment = arr.length / 2; increment > 0; increment = increment / 2) {
    
                for (int i = increment; i < arr.length; i++) {
                    int j = i;
                    int temp = arr[j];
                    if (arr[j] < arr[j - increment]) {
                        while (j - increment >= 0 && temp < arr[j - increment]) {
                            arr[j] = arr[j - increment];
                            j -= increment;
                        }
                        arr[j] = temp;
                    }
                }
                System.out.println(Arrays.toString(arr));
            }
    

2.5 Quick Sort

Thought: Quicksort is an improvement of the bubble sort, the sort will trip by data to be sorted into two separate portions, wherein a portion of all the data smaller than any other portion of the data, then this method of the two parts of the data were quick sort, the entire sorting process can be recursively in order to achieve the entire data becomes an ordered sequence.

public static void quickSort(int[] arr,int left,int right){
        int l=left;
        int r=right;
        int temp=0;
        int privot=arr[(right+left)/2];
       while (l<r){
           while (arr[l]<privot){
                l++;
           }
           while (arr[r]>privot){
               r--;
           }
           if(l>=r){
               break;
           }
           temp=arr[l];
           arr[l]=arr[r];
           arr[r]=temp;

           if(arr[l]==privot){
               r--;
           }
           if(arr[r]==privot){
               l++;
           }
       }
       if(l==r){
           l+=1;
           r-=1;
       }
       //左递归
        if (left<r){
            quickSort(arr,left,r);

        }
        //向右递归
        if(right>l){
            quickSort(arr,l,right);
        }
    }

2.6 merge sort (mergesort)

Merge sort idea is to use merge sort method, using the classic divide and conquer strategy (divide and conquer is to break the problem into smaller problems and then recursive solution, then it will answer all stages of patching together)

Find online graphic
Here Insert Picture Description
such a structure would like a complete binary tree, we use the recursive method to achieve, you can also take an iterative approach to achieve a phased process can be understood as a recursive partitioning sequence.

  • Split sequence

        public static void mergeSort(int[] arr, int left, int right, int[] temp) {
            if (left < right) {
                int mid = (left + right) / 2;
                //向左递归分解
                mergeSort(arr, left, mid, temp);
                //向右递归分解
                mergeSort(arr, mid + 1, right, temp);
                //合并
                 merge(arr, left, mid, right, temp);
            }
        }
    
  • The combined sequence

    /**
         * 合并
         *
         * @param arr   原始数组,待排序的数组
         * @param left  数组的左边坐标
         * @param mid   数组的中间坐标
         * @param right 数组的右边坐标
         * @param temp  临时数组
         */
        public static void merge(int[] arr, int left, int mid, int right, int temp[]) {
            int i = left;//初始化i,左边序列的初始索引
            int j = mid + 1;//初始化j,右边序列的初始索引
            int t = 0; //临时变量的索引
            //1、将拆开的左右数组中的元素分别比较大小,并放入临时数组,直至某一数组被放完
            while (i <= mid && j <= right) {
                if (arr[i] < arr[j]) {
                    temp[t] = arr[i];
                    i++;
                    t++;
                } else {
                    temp[t] = arr[j];
                    j++;
                    t++;
                }
            }
    
            //2、将剩下数组的元素全部移动到临时数组中
            while (i <= mid) {
                temp[t] = arr[i];
                i++;
                t++;
            }
            while (j <= right) {
                temp[t] = arr[j];
                j++;
                t++;
            }
            //3 将临时数组的元素合更新到原数组
            t = 0;
            int tempLeft = left;
            while (tempLeft <= right) {
                arr[tempLeft] = temp[t];
                t++;
                tempLeft++;
            }
    
        }
    

2.7 Radix Sort (bucket sort of extension)

Algorithm Description: digital radix sort is separated for each one, according to each of a specified size into the bucket, the bucket is represented by an array, divided into numbered 0-9 tub. Such as 249, the separation bits, numbered 249 into the tub 9, when the ten isolated, numbered 246 into the tub 4, one thousand isolated position, the bucket 249 into the number of 0. Sequence present negative radix sort can not be used.

The basic idea: all to be compared numerical unity for the same digit length, number of bits shorter front complement to zero, and then, from the lowest Start, once sorted, so from the lowest sort until after the highest sort is complete, the number of columns it becomes an ordered sequence.

 public static void radisSort(int[] arr){
        //找出最大数并确定位数
        int max=arr[0];
        for(int i=1;i<arr.length;i++){
            if(max<arr[i]){
                max=arr[i];
            }
        }
        int maxLength=(max+"").length();
        //定义桶,为了防止元素溢出,需要将每个桶的容量都定义为:arr.length
        int[][] bucket=new int[10][arr.length];
        //定义一个数组bucketElementCount[],用来记录每个桶中放入的元素的数量
        int[] bucketElementCount=new int[10];
        /**
         * 将数据元素放入桶中
         */
        for(int l=0,n=1;l<maxLength;n=n*10,l++){
            for(int i=0;i<arr.length;i++){
                int endDigital=arr[i]/n%10;
                bucket[endDigital][bucketElementCount[endDigital]]=arr[i];
                bucketElementCount[endDigital]++;
            }
            /**
             * 取出元素
             */
            int index=0;
            for(int i=0;i<bucket.length;i++){
                if(bucketElementCount[i]!=0){
                    for(int j=0;j<bucketElementCount[i];j++){
                        arr[index]=bucket[i][j];
                        index++;
                    }
                }
            //将bucketElemnetCount清零
                bucketElementCount[i]=0;
            }
            System.out.println(Arrays.toString(arr));
        }

    }

2.8 sorting algorithm summary

Here Insert Picture Description

Published 71 original articles · won praise 42 · views 60000 +

Guess you like

Origin blog.csdn.net/dreame_life/article/details/104131645