Sorting operation of array

Keywords: Java less

There are many sorting algorithms, including Insertion sortBubble sortHeap sortMerge sort , select sort, Counting sortRadix sortingBucket sortingQuick sort And so on. Insert sort, heap sort, select sort, merge sort, fast sort, bubble sort are all comparative sort. They sort by comparing the elements in the array. Other sorting algorithms use other non comparative methods to get the information about the sorting of input array.

Bubble sort

Bubble sort, unstable (will change the position of most array values)

The core algorithm of bubble sorting is to get the best value at a time

Time complexity of bubble sorting:

The time complexity of bubble sorting is O(n) in the best case and O(n^2) in the worst case.

Number of bubble sorts:

Compare N numbers N-1 times.

Principle:

For an array, the bubble sorting algorithm compares the size of two adjacent items and exchanges them.
Make the same adjustments to each pair of adjacent elements, such as the first and second, the second and third, the third and fourth, and so on. In this way, the last element will be the largest.
Repeat the above steps. If there are n elements, the first cycle n-1 times, the second cycle n-2 times , after the n-j cycle, the larger number of J will be discharged in order of size.
Continue the above steps until there is no pile of numbers to compare.

Train of thought:

Compare the two adjacent numbers in turn, put the decimal number in front and the large number in the back. That is, in the first pass: first, compare the first and second numbers, put the decimal number before and the large number after. Then compare the second number and the third number. Put the decimal number before and the large number after. Continue until the last two numbers are compared. Put the decimal number before and the large number after. Repeat the first step until all sorting is complete.

For example: to sort arrays: int[] array={6,3,8,2,9,1}

public class BubbleSort {
/**
 * N The numbers need to be sorted. There are N-1 times in total. The sorting times of each I times are (N-i). Therefore, the double loop statement can be used. The outer layer controls the number of cycles and the inner layer controls the number of cycles.
 * @param args
 */
    public static void main(String[] args) {
        int arr[] = {26,15,29,66,99,88,36,77,111,1,6,8,8};
        for(int i=0;i < arr.length-1;i++) {//Outer loop control sorting times
            for(int j=0; j< arr.length-i-1;j++) {
                        //Inner loop controls how many times each sorting
                // Swap small values to the front
                if (arr[j]>arr[j+1]) {
                    int temp = arr[j];
                    arr[j] = arr[j+1];
                    arr[j+1] = temp;
                }
            }
            System.out.print("The first"+(i+1)+"Secondary sorting result:");
                                //List data for each sort
            for(int a=0;a<arr.length;a++) {
                System.out.print(arr[a] + "\t");
            }
            System.out.println("");
        }
        System.out.println("Final sorting result:");
        for(int a = 0; a < arr.length;a++) {
            System.out.println(arr[a] + "\t");
        }
    }
}

Selection sort

Selection sort is a simple and intuitive sorting algorithm.

Selection sorting, unstable (will change the value of the original position of most arrays)

Select sort is to compare each number with all the numbers after it

Working principle:

For the first time, select the smallest (or largest) element from the data elements to be sorted, store it at the beginning of the sequence, then find the smallest (large) element from the remaining unsorted elements, and then put it at the end of the sorted sequence. And so on until the number of all data elements to be sorted is zero. Selection sort is an unstable sort method

{8 , 2 , 3 , 7 , 1}
Round 1: {1 | 8, 3, 7, 2}
Round 2: {1, 2 | 8, 7, 3}
Round 3: {1, 2, 3 | 8, 7}
Round 4: {1, 2, 3, 7 | 8}
Round 5: {1, 2, 3, 7 | 8}

The first layer of the selection sorting method selects from the starting element to the penultimate element. It is mainly to assign the subscript of the outer layer to the temporary variable before the second layer of each entry. In the next second layer of the loop, if there is an element smaller than the element at the minimum position, then assign the subscript of the smaller element to the temporary variable. Finally, After the exit of the second level loop, if the temporary variable changes, it means that there are smaller elements than the current outer level loop, and the two elements need to be exchanged

Select the time complexity of sorting:

The time complexity of selection sorting is O(n^2).

For example:

public static void selectionSort(int[] arr){
    int min, temp;
    for (int i = 0; i < arr.length; i++) {
        // Initializing the minimum data array subscript in an unsorted sequence
        min = i;
        for (int j = i+1; j < arr.length; j++) {
            // Continue to find the smallest element in the unsorted element and save its subscript
            if (arr[j] < arr[min]) {
                min = j;
            }
        }
        // Place the smallest element in the unordered sequence at the end of the ordered sequence
        if (min != i) {
            temp = arr[min];
            arr[min] = arr[i];
            arr[i] = temp;
        }
    }
}

Insertion sort

Insert sort, stable (change the position of some array values) (the worst time complexity O(n^2) is O(n))

The core of insertion sorting algorithm is to change the current insertion position into order

Principle: divide the sequence of n elements into ordered and unordered parts, as shown in the example of insertion sorting process:

{{a1},{a2,a3,a4,...,an}}    

{{a1⑴,a2⑴},{a3⑴,a4⑴ ...,an⑴}}    

{{a1(n-1),a2(n-1) ,...},{an(n-1)}}    

For example, {101, 34, 119, 1} is derived step by step

Round 1 {101, 34, 119, 1}; = > {34, 101, 119, 1}

{101, 34, 119, 1}; => {101,101,119,1}

{101,101,119,1}; => {34,101,119,1}

Round 2 {34, 101, 119, 1}; = > {34, 101, 119, 1}

Round 3 {34, 101, 119, 1}; = > {1, 34, 101, 119}

{34, 101, 119, 1};  => {34, 101, 119, 119}

{34, 101, 119, 119};  => {34, 101, 101, 119}

{34, 101, 101, 119};  => {34, 34, 101, 119}

{34, 34, 101, 119};  => {1, 34, 101, 119}

There are two situations in which insertion sorting is suitable:

Select when each element is not far from its final position

For arrays with fewer elements, we can insert and sort the fastest (if N is too small to be affected by the coefficient)

Each processing is to compare the first element of the disordered sequence with the elements of the ordered sequence one by one from the back to the front, find out the insertion position, and insert the element into the appropriate position of the ordered sequence.

Code demo

import java.util.Arrays;

public class Test {
public static void main(String[] args) {
	int[] array={12,73,45,69,35};
	int i,j,temp;
	for(i=1;i<array.length;i++) {
		/*
		 * First for loop
		 * Divide the array into two parts, unsorted on the right and sorted on the left
		 * Record sort and unsorted split point temp (temp is the next sort object)
		 */
		temp=array[i];
		for(j=i-1;j>=0;j--) {
		/*
		 * Second for loop
		 * Compare sort object temp with sorted array
		 * When temp is larger than the nearest number on the left (in descending order)
		 * Directly end this cycle and sort the next number
		 * Otherwise, move the number back a few hours later than the one on the left to make room for the number
		 */
		   if (temp > array[j]) {
				break;
		   }else{
	    	   array[j+1] = array[j];
	       }
		}
		array[j+1]=temp;
	}
	System.out.println(Arrays.toString(array));
}
}

Counting sort

The count sort is suitable for the current array intensive situation. For example (2,3,5,4,2,3,3,2,5,4)

Method:

First find out the maximum value and the minimum value, then count the number of times each number appears, and add it to the array according to the number from small to large

Counting sort method is a sort method without comparison

Core idea:

Regularize numbers and corner marks

Thoughts on counting and sorting

Count sorting is applicable to arrays with a clear range, such as given an array, and knowing that all the value ranges are [m,n]. At this time, an array of n-m+1 length can be used, and the array to be sorted can be scattered on this array. The value of the array is the number of current values. After another iteration and expansion, the array will be in order.

  1. Create a new temporary array of length n-m+1
  2. Traversing the array to be sorted, its value - m is used as the bottom corner of the temporary array, and the value of this position is increased by 1
  3. At the end of traversal, the temporary array stores the number of each value
  4. Finally, expand it and assign it to the original array

Code

 1 //Counting sort
 2 void CountSort(int *a, int size)
 3 {
 4     int max = a[0];
 5     int min = a[0];
 6     for (int i = 0; i < size; ++i)
 7     {
 8         if (a[i] > max)
 9             max = a[i];
10         if (a[i] < min)
11             min = a[i];
12     }
13     int range = max - min + 1; //Array range to open
14     int *count = new int[range];
15     memset(count, 0, sizeof(int) * range); //Initialize to 0
16                                            //Count the number of times each number appears
17     for (int i = 0; i < size; ++i)           //Get data from the original array. The number of the original array is size
18     {
19         count[a[i] - min]++;
20     }
21     //Write back to the original array
22     int index = 0;
23     for (int i = 0; i < range; ++i) //Read from the opened array. The size of the opened array is range
24     {
25         while (count[i]--)
26         {
27             a[index++] = i + min;
28         }
29     }
30     delete[] count;
31 }
Four sort summaries:
class Test02{
    public static void main(String[] args){
        //1. Select sort O(n^2)
        selectSort();
        //2. Bubble sort O(n^2)
        bubbleSort();
        //3. Insert sort O(n^2) 
        insertSort();
        //4. Count sort O(n+m)
        /*
        The above three sorts are based on the size relationship between the data
        The counting cardinality bucket is based on the characteristics of the data itself to compare size independent sorting
        These sorts are only for integers
        It's a typical order of sacrificing space for time
        */
        countSort();

    }
    public static void countSort(){
        int[] arr={8,5,9,2,7,4,6,1,3,10,-3,-2,-10};
        int min=arr[0];
        int max=arr[0];
        for(int i=0;i<arr.length;i++){//O(n)
            if(arr[i]>max){
                max=arr[i];
            }
            if(arr[i]<min){
                min=arr[i];
            }
        }
        int[] nums=new int[max-min+1];
        int offset=min;
        for(int i=0;i<arr.length;i++){//O(n)
            nums[arr[i]-offset]++;
        }
        int index=0;
        for(int i=0;i<nums.length;i++){//O(m)
            if(nums[i]!=0){
                for(int j=0;j<nums[i];j++){
                    arr[index++]=i+offset;
                }
            }
        }
        show(arr);
    }
    public static void insertSort(){
        int[] arr={8,5,9,2,7,4,6,1,3};
        int e;
        int j;
        for(int i=1;i<arr.length;i++){
            e=arr[i];
            for(j=i;j>0&&arr[j-1]>e;j--){
                arr[j]=arr[j-1];
            }
            arr[j]=e;
        }
        /*
        for(int i=1;i<arr.length;i++){
            for(int j=i;j>0&&arr[j-1]>arr[j];j--){
                swap(arr,j,j-1);
            }
        }
        */
        show(arr);
    }
    //How to optimize yourself? Anyway, I told you that you don't need to write your own code
    public static void bubbleSort(){
        int[] arr={8,5,9,2,7,4,6,1,3};
        for(int i=0;i<arr.length-1;i++){//-1. One less round of comparison
            for(int j=0;j<arr.length-1-i;j++){//-1 avoid repeated comparison and corner mark crossing
                if(arr[j]>arr[j+1]){
                    swap(arr,j,j+1);
                }
            }
        }
        show(arr);
    }
    public static void selectSort(){
        int[] arr={8,5,9,2,7,4,6,1,3};
        for(int i=0;i<arr.length-1;i++){//-1 because there is no need to compare the last number
            for(int j=i+1;j<arr.length;j++){
                if(arr[i]>arr[j]){
                    swap(arr,i,j);//Ready to use - ready to release
                }
            }
        }
        show(arr);
    }
    public static void swap(int[] arr,int i,int j){
        //1. Exchange with three party variables 
        //Common for all data types
        /*
        int temp=arr[i];
        arr[i]=arr[j];
        arr[j]=temp;
        */
        //2. Exchange with addition and subtraction
        //Only applicable to digital related data types
        arr[i]=arr[i]+arr[j];
        arr[j]=arr[i]-arr[j];
        arr[i]=arr[i]-arr[j];

        //3. Exchange with bit operation
        //Only for integer related data types
        /*
        int a=3;
        int b=7;
        a=a^b;
            0011
            0111
            0100
        b=a^b;
            0100
            0111
            0011 ->3
        a=a^b;
            0100
            0011
            0111 ->7
        */
    }
    public static void show(int[] arr){
        //[1,2,3,4,5,6,7,8,9]
        String s="[";
        for(int i=0;i<arr.length;i++){
            if(i==arr.length-1){
                s+=arr[i]+"]";
            }else{
                s+=arr[i]+",";
            }
        }
        System.out.println(s);
    }
}

 

Published 52 original articles · praised 3 · visited 1322
Private letter follow

Posted by ukscotth on Mon, 17 Feb 2020 22:08:01 -0800