[Appendix 1 common algorithms in Java arrays] the ten sorting algorithms are illustrated and explained in detail, giving you endless aftertaste

Posted by Joefunkx on Mon, 10 Jan 2022 21:08:19 +0100

❤ Write in front
❤ Blog home page: Hard working Naruto
❤ Series column: Java basic learning 😋
❤ Welcome, friends, praise 👍 follow 🔎 Collection 🍔 Learning together!
❤ If there are mistakes, please correct them! 🌹

🚩 In recent java learning, I found that many basic knowledge of Java are forgotten and fuzzy. I plan to sort out all [Java], and successive articles will be put here. Welcome to subscribe and learn together > > > Java basic learning 😋

Book connection > > > portal: [[[chapter 03 Java arrays] programmers must see the detailed explanation of arrays]

1, Sorting algorithm

  1. Sorting: suppose the sequence containing n records is {R1, R2,..., Rn}, and the corresponding keyword sequence is {K1, K2,..., Kn}. Reorder these records into {Ri1,Ri2,..., Rin}, so that the corresponding keyword values meet the requirements of Ki1 < = ki2 < =... < = kin. Such an operation is called sorting.
  2. Measure the advantages and disadvantages of sorting algorithm:
    ● time complexity: analyze the comparison times of keywords and the movement times of records
    ● spatial complexity: analyze how much auxiliary memory is required in the sorting algorithm
    ● stability: if the keyword values of two records A and B are equal, but the order of A and B remains unchanged after sorting, the sorting algorithm is said to be stable.

👌 Top ten internal sorting algorithms

Select sort
 1. Direct selection sort
 2. Heap sort
Exchange sort
 3. Bubble sorting
 4. Quick sort
Insert sort
 5. Direct insert sort
 6. Binary Insertion Sort
 7.Shell sort
 8. Merge sort
 9. Bucket sort
 10. Cardinality sort

👌 Direct selection sort

  1. Sorting idea: generally, the first element is used as the reference value, and it is compared with the reference value from the second element. When it is larger than the reference value, it is placed behind the reference value, and when it is smaller than the reference value, it is compared with the previous position of the reference value. When it is compared to the appropriate position, it is inserted

  2. Input: array element, array r, to be sorted interval of array r [low,high]
    Output: array r ordered by keyword
    The code is as follows:

public void insertSort(Object[] r,int low,int high){
  for(int i = low +1;i<=high;i++){ //When less than, r[i] needs to be inserted into the sequence table
    if(r[i] < r[i-1]){
      Object temp = r[i];
      r[i]  = r[i-1];
      int j=i-2;
      for(;j>=low&&temp < r[j];j++){
      r[j+1] = r[j];//Record backward
      }
      r[j+1] = temp;//Insert in the correct position
    }
  }
}

👌 Heap sort

  1. Definition: it refers to a sort algorithm designed by using the data structure of heap. Heap is a structure similar to a complete binary tree and satisfies the nature of heap: that is, the key value or index of a child node is always less than (or greater than) its parent node.
  2. Look at the picture and think:
  3. Sorting idea: the sequence to be sorted is constructed into a large top heap. At this time, the maximum value of the whole sequence is the root node at the top of the heap. Swap it with the end element, where the end is the maximum. Then reconstruct the remaining n-1 elements into a heap, which will get the sub small value of n elements. If you execute it repeatedly, you can get an ordered sequence

🎁 Note: large top heap: the value of each node is greater than or equal to the value of its left and right child nodes
Small top heap: the value of each node is less than or equal to the value of its left and right child nodes

  1. The code is as follows:
public class HeapSort {
    public static void main(String[] args) {
        int[] a = {24, 10, 5, 1, 2, 24, 5, 1, 2, 5, 7, 8, 5, 3, 7, 63, 9, 0, 42, 3, 8, 24, 1};
        long start = System.currentTimeMillis();
        heapSort(a);
        System.out.println(Arrays.toString(a));
        System.out.println("Time use:" + (System.currentTimeMillis() - start));
    }

    private static void heapSort(int[] a) {
        //Initialize the maximum heap, starting from the penultimate layer
        for (int i = a.length/2; i >=0; i--) {
            sortDownHeap(a,a.length,i);
        }
        //push the top of the heap element last and rebuild the maximum heap
        for (int i = a.length-1; i >=0 ; i--) {
            swap(a,0,i);
            sortDownHeap(a,i-1,0);
        }
    }
    //Maximum heap down adjustment
    private static void DownHeap(int[] a, int length, int i) {
        int t = i+1;
        while (2*t <= length) {
            int tmpMax = t;// Record the maximum subscript in the parent-child node
            if (a[t - 1] < a[2 * t - 1]) { 
                tmpMax = 2 * t;
            }
            if (a[tmpMax - 1] < a[2 * t]) {
                tmpMax = 2 * t + 1;
            }
            if (tmpMax != t) {  // If the current root node is not the maximum
                swap(a, t - 1, tmpMax - 1);
                t = tmpMax;// Continue to adjust downward
            } else {
                return;// Stop adjustment
            }
        }
    }
    private static void swap(int[] a, int i, int j) {
        int tmp = a[i];
        a[i] = a[j];
        a[j] = tmp;
    }
}

👌 Bubble sorting

  1. Let's look at the picture first:
  2. Bubble sorting idea:
    ● compare adjacent elements. If the first one is larger than the second (in ascending order), exchange them.
    ● do the same work for each pair of adjacent elements, from the first pair at the beginning to the last pair at the end. After this step, the last element will be the maximum number.
    ● repeat the above steps for all elements except the last one.
    ● continue to repeat the above steps for fewer and fewer elements each time until there is no pair of numbers to compare.
  3. The code is as follows:
public class Test {
	public static void main(String[] args) {
		int[] array = { 6, 1, 4, 3, 8, 6, 4, 9, 7 };
		int len = array.length;
		System.out.println("The array before sorting is:"+Arrays.toString(array));
		int temp = 0;
		for (int i = 0; i < len - 1; i++) {
			for (int j = 0; j < len - 1 - i; j++) {
				if (array[j] > array[j + 1]) {
					temp = array[j + 1];
					array[j + 1] = array[j];
					array[j] = temp;
				}
			}
		}
		System.out.println("The sorted array is:"+Arrays.toString(array));
	}
}


👌 Quick sort

Quick Sort was invented by Tony Hoare, a Turing prize winner. It is listed as one of the top ten algorithms in the 20th century and the fastest of all internal sorting algorithms so far. Bubble sort upgrade, a kind of exchange sort.

  1. The time complexity of quick sort is O(nlog(n)).
  2. Thought:
    ● select an element from the sequence, which is called the benchmark
    ● reorder the sequence. All elements smaller than the benchmark value are placed in front of the benchmark, and all elements larger than the benchmark value are placed behind the benchmark (the same number can be on either side). At the end of this partition, the benchmark is in the middle of the sequence
    ● recursively sort the subsequence less than the reference value element and the subsequence greater than the reference value element.
    ● the bottom case of recursion is that the size of the sequence is zero or one, that is, it has always been sorted. Although it recurses all the time, the algorithm will always end, because in each iteration, it will put at least one element to its last position.
  3. Time complexity
    It performs better when the average time complexity is O (N*logN) and the array is unordered
    The worst time complexity is when the O (N^2) array is ordered and in reverse order

👌 Direct insert sort

  1. Idea: look at the n elements to be sorted as an ordered table and an unordered table. At the beginning, the ordered table contains only one element, and the unordered table contains n-1 elements. In the sorting process, take the first element from the unordered table every time, compare its sorting code with the sorting code of the elements of the ordered table, and insert it into the appropriate position in the ordered table, Make it a new ordered table
    Simply put: take out the values one by one from a group of unordered arrays and put them in the appropriate position in the ordered array to make the ordered array ordered again until the unordered array is empty and the loop ends
  2. The code is as follows:
public class InsertSort{
    public static void insSort(int[] a){
        for(int i=0; i<a.length; i++){
            int tmp = a[i];
            int j = 0;
            //Insert the ith value into the appropriate position in the current i-1
            for(j=i; j>0&&tmp<a[j-1]; j--){
                //Traverse from the back to the front. If the tmp value is smaller, it means that its position needs to be closer to the front
                //So move back one position in turn
                a[j] = a[j-1];
            }
            a[j] = tmp;
        }
    }
    public static void main(String args[]){
        int[] test = {5,9,4,1,2};
        insSort(test);
        for(int i=0; i<test.length; i++){
            System.out.print(test[i] + " ");
        }
    }
}

👌 Binary Insertion Sort

  1. Sorting thought
    ● 1 treat the first element as an element of a search area. At first, the search area only contains ary[0] (the first element)
    ● 2 take out the next element (obtained circularly here, starting from the second element) and compare it with the middle element (semi search method) of the search area. Note: the elements in the search area are in order
    ● 3 if the new element is smaller than the middle element, move the right boundary (represented by the right variable) of the search area to the left by one bit; if it is greater than or equal to the middle element, move the left boundary (represented by the left variable) to the left by one bit
    ● 4 repeat step 3 until the left boundary is greater than the right boundary
    ● 5 judge whether the left boundary is in the search area. If so, move backward one bit from the found index position to the end of the index position of the comparison element. If it is outside the right boundary, ignore this step
    ● 6 overwrite the found location elements with the compared elements (the data taken out in the second step)
    ● 7 repeat step 2
  2. The example code is as follows:
public void binaryInsertSort(int[] arr) {
    // Take bit 0 of the array as an ordered sequence and insert it one by one from bit 1
    for (int i = 1; i < arr.length; i++) {
        int temp = arr[i];
        int low = 0;
        int high = i - 1;
        // Use the half find method to find the location to insert
        while (low <= high) {
            int mid = (low + high) / 2;
            if (temp < arr[mid]) {
                high = mid - 1;
            } else {
                low = mid + 1;
            }
        }
        // Backward shift
        for (int j = i - 1; j >= mid; j--) {
            a[j+1] = a[j];
        }
        arr[mid] = temp;// Insert element 
    } 
}

👌 Shell sort

  1. Idea: the whole element sequence to be arranged is divided into several sub sequences for direct insertion sorting. When the elements in the whole sequence are basically in order, all elements will be directly inserted and sorted again

👌 Merge sort

  1. Idea: first divide the array into two parts from the middle, then sort the two parts respectively, and then merge the two parts in good order

👌 Bucket sort

Only non negative sorting is supported

  1. The sequence to be sorted meets the following two characteristics:
    ● all values of the sequence to be arranged are within an enumerable range
    ● the enumerable range of the sequence to be arranged should not be too large, otherwise the sorting efficiency is too low
  2. The steps are as follows:
    ● for this enumerable range, build a buckets array to record the number of elements "falling" into each bucket;
    ● recalculate the buckets array obtained in (1) according to the following formula:
    buckets[i] = buckets[i] +buckets[i-1] (where 1 < = I < buckets. Length);

👌 Cardinality sort

👌 Five characteristics of the algorithm

🎁 Summary: the ten internal sorting algorithms in the array are also widely used in peacetime. Under this arrangement, it is convenient to learn in the future

👌 The author is a Java beginner. If there are errors in the article, please comment and correct them in private letters and learn together~~
😊 If the article is useful to the friends, praise it 👍 follow 🔎 Collection 🍔 Is my biggest motivation!
🚩 Step by step, nothing to a thousand miles, book next time, welcome to see you again 🌹

Topics: Java Algorithm