6 sorting methods (you won’t regret the click)

1. Bubble sorting
Let’s look at the example directly.
Suppose there are 5 numbers:
5 4 3 2 1
We have to arrange them in ascending order. Normal thinking we would do this.

5 4 3 2 1
4 5 3 2 1
4 3 5 2 1
3 4 5 2 1
3 4 2 5 1


Compare the two adjacent numbers at a time and change the smaller ones to the front.
Average complexity O(n^2)

class sort{
    
    

   static void onesort(int a[]){
    
    //要排序的数组
        boolean flag=true;//判断交换是否还需要继续进行
        while (flag) {
    
    
            flag=false;
            for (int i = 1; i < a.length-1;i++) {
    
    
                if(a[i]>a[i+1]){
    
    
                    int x=a[i];
                    a[i]=a[i+1];
                    a[i+1]=x;
                    flag=true;//因为开始我们已经改成了false,如果没有可进行交换的flag就会是false  函数也就不会继续进行,这样会大大节省时间
                }


            }
        }
    }
}

2. Select sorting
First find the smallest (large) element in the unsorted sequence and store it at the beginning of the sorted sequence.

Then continue to find the smallest (large) element from the remaining unsorted elements, and then put it at the end of the sorted sequence.

Repeat the second step until all elements are sorted

Or this example:

5 4 3 2 1
1 4 3 2 5
1 2 3 4 5

Average complexity O(n^2)


void swap(int *a,int *b) //交换函数
{
    
    
    int temp = *a;
    *a = *b;
    *b = temp;
}
void selection_sort(int arr[], int len)
{
    
    
    int i,j;

        for (i = 0 ; i < len - 1 ; i++)
    {
    
    
                int min = i;
                for (j = i + 1; j < len; j++)     //遍历剩余未排序元素
                        if (arr[j] < arr[min])    //找到目前最小值
                                min = j;    //记录最小值
                swap(&arr[min], &arr[i]);    //做交換
        }
}

Usually selection sort is better than bubble sort, bubble sort is exchanged in the inner loop, and selection sort is exchanged in the outer loop. The efficiency is poor in this number of exchanges, after all, O(n)<O(n^2). If the array is completely ordered, the exchange within the bubbling loop will not be executed once, and the selection sort will have to be exchanged with itself each time, and the bubbling efficiency is high at this time. But this kind of situation is very rare, so from the point of view of algorithm, choice is better than bubbling


3. Insertion sorting
In a set of numbers to be sorted, assuming that the first n-1 numbers are already in order, now insert the nth number into the front ordered number column, so that the n numbers are also in order . Repeat this cycle until all are arranged in order.

The example is as follows:
5 4 3 2 1
Insert
5 from the second number. 4 Unsorted: 3 2 1
Because 4 is smaller than 5, it is inserted before
5. 4 5 Unsorted: 3 2 1
3 4 5 Unsorted: 2 1

public static void  insert_sort(int array[],int lenth){
    
    

   int temp;

   for(int i=0;i<lenth-1;i++){
    
    
       for(int j=i+1;j>0;j--){
    
    
           if(array[j] < array[j-1]){
    
    
               temp = array[j-1];
               array[j-1] = array[j];
               array[j] = temp;
           }else{
    
             //不需要交换
               break;
           }
       }
   }
}

4. Hill sorting
Hill sorting can be regarded as an enhanced version of insertion sorting. It uses the efficiency of insertion sorting when the amount of data is small and when the data is relatively orderly, to logically group an array by the distance of the index. Then insert sort for each group
Insert picture description here

public static void shell_sort(int array[],int lenth){
    
    

   int temp = 0;
   int incre = lenth;

   while(true){
    
    
       incre = incre/2;

       for(int k = 0;k<incre;k++){
    
        //根据增量分为若干子序列

           for(int i=k+incre;i<lenth;i+=incre){
    
    //当incre(也就是k)确定时,因为至少要2个元素才能进行插入排序,所以要插入的元素从k+incre开始枚举(第一个元素下标为k)

               for(int j=i;j>k;j-=incre){
    
    //依次用要插入的元素和前一个元素做比较
                   if(array[j]<array[j-incre]){
    
    //比它小就交换,例如往 3 5 7 中插入4  
                                               /*3 5 4 7
                                               	 3 4 5 7
                                               */
                       temp = array[j-incre];
                       array[j-incre] = array[j];
                       array[j] = temp;
                   }else{
    
    
                       break;//无法交换就退出
                   }
               }
           }
       }

       if(incre == 1){
    
    
           break;//当incre为1时  整个数列分为了一组,进行插入排序一定是有序的故直接退出while
       }
   }
}

5. Merge sort
The core idea of ​​merge sort is divide and conquer. The straightforward point is to divide the array that needs to be sorted into many small arrays for sorting. It is similar to quick sort
Insert picture description here(picture from Zhihu)

In the figure, we divide the unsorted sequence until it is divided into one data, and then merge these data together in pairs to make it orderly, and continuously merge, and finally become a sorted sequence.

static void merge_sort_recursive(int[] arr, int[] result, int start, int end) {
    
    
    if (start >= end)//正常情况开头是大于结尾的,除非已经分割成单个元素,则此时返回
        return;
    int len = end - start, mid = (len >> 1) + start;//len >> 1位运算,相当于除2
    //找出当前数列中间的位置
    int start1 = start, end1 = mid;//分割成2个数列
    int start2 = mid + 1, end2 = end;
    merge_sort_recursive(arr, result, start1, end1);//递归下去,对2个子序列排序
    merge_sort_recursive(arr, result, start2, end2);
    //经过上面的递归,start1~end1  ,start2~end2已经是有序的了
    int k = start;
    while (start1 <= end1 && start2 <= end2)
        result[k++] = arr[start1] < arr[start2] ? arr[start1++] : arr[start2++];//从2个有序的里面选出小的
        /*1 4 7 8 9
          2 3 5 
          第一个选1
          第二个选2 
          第三个选3
          .... 
		*/
        
    while (start1 <= end1)//因为start1 <= end1 && start2 <= end2  中 有一个条件会先不满足,那么存在一个满足仍然是满足的,说明有元素没有赋值到 result数组,所以要加上
        result[k++] = arr[start1++];
    while (start2 <= end2)
        result[k++] = arr[start2++];
    for (k = start; k <= end; k++)
        arr[k] = result[k];
}

public static void merge_sort(int[] arr) {
    
    
    int len = arr.length;
    int[] result = new int[len];
    merge_sort_recursive(arr, result, 0, len - 1);
}

6. Quick sort (the picture comes from the aha algorithm)
should be the most used. The sorting algorithm in many languages ​​stl basically uses quick sort. Above we said that it has the same effect as merge sort, but there are also differences;
Difference:
The strategy for grouping is different, and the strategy for merging is also different. The grouping strategy of merging is to assume that the elements to be sorted are stored in an array, and then the first half of the elements of the array are regarded as one group, and the latter half are regarded as another group. The quick sort is based on the value of the element, a group of elements greater than a certain value, a group of elements less than a certain value.
Quick sort has been grouped according to the size of the elements when grouping, and when merging, you only need to merge the two groups, and merge sorting needs to merge the two ordered arrays according to the size;

Now let's take a look at how to operate quick sort;

1. First we need to set a base number as the dividing point, generally we select the leftmost number of the array;

2. With the cardinality, we respectively traverse the array from left to right and from right to left, remembering to proceed at the same time

Insert picture description here
3. Until we find a number less than the base number, and a number greater than the base number, then we exchange it;

Insert picture description here
(3 operations were performed many times)

4. As shown in the figure, when the two soldiers meet, the array will be traversed.

Insert picture description here
At this time 6 (base) is greater than 3, we just align and exchange.
Insert picture description here
At this time, the left side of 6 is all numbers less than 6, and the right side is numbers greater than 6, and then the 2 blocks are divided into 2 arrays and recursively, until the recursion becomes one. An array of size 2
Insert picture description here
and then we can merge these arrays to get an ordered array;

blic class QuickSort {
    
    
    public static void main(String[] args) {
    
    
        Scanner scan=new Scanner(System.in);
        int[] arr=new int[10];
        for(int i=0;i<10;i++){
    
    
            arr[i]=scan.nextInt();
        }
        QuickSort(arr, 0, arr.length-1);
        for (int i = 0; i < arr.length; i++) {
    
    
            System.out.println(arr[i]);
        }

    }
    public static void QuickSort(int[] arr,int low,int high){
    
    
        int i,j,temp,t;
        if(low>high){
    
    
            return;
        }
        i=low;
        j=high;
        //temp就是基准位
        temp = arr[low];

        while (i<j) {
    
    
            //先看右边,依次往左递减
            while (temp<=arr[j]&&i<j) {
    
    
                j--;
            }
            //再看左边,依次往右递增
            while (temp>=arr[i]&&i<j) {
    
    
                i++;
            }
            //如果满足条件则交换
            if (i<j) {
    
    
                t = arr[j];
                arr[j] = arr[i];
                arr[i] = t;
            }

        }
        //最后将基准为与i和j相等位置的数字交换
        arr[low] = arr[i];
        arr[i] = temp;
        //递归调用左半数组
        QuickSort(arr, low, j-1);
        //递归调用右半数组
        QuickSort(arr, j+1, high);
    }
}

Guess you like

Origin blog.csdn.net/jahup/article/details/106607236