0Basic C# Notes 08: Insertion Sort Method


Preface

When we were playing cards, how did you organize the cards? A simple way to do this is to go one by one, inserting each card into its appropriate position among the other cards that are already sorted. When we sort an unordered array, in order to insert elements, we need to make space and move all remaining elements one position to the right before inserting. This algorithm is called insertion sort.


1. Brief description of the process:

1. Extract elements starting from the second element of the array.

2. Compare it with the first element on the left. If the first element on the left is larger than it, continue to compare it with the second element on the left until it encounters an element that is no larger than it, and then insert it to the right of this element.

3. Continue to select the 3rd, 4th,...n elements, repeat step 2, and select the appropriate position to insert.

I have also prepared animations for easier understanding:
Insert image description here
If you still don’t understand, I have also prepared a high-quality article to explain: Insertion Sort

2. Code

public class InsertSort {
    
    
    public static int[] insertSort(int[] arr) {
    
    
        if(arr == null || arr.length < 2)
            return arr;

        int n = arr.length;
        for (int i = 1; i < n; i++) {
    
    
            int temp = arr[i];
            int k = i - 1;
            while(k >= 0 && arr[k] > temp)
                k--;
            //腾出位置插进去,要插的位置是 k + 1;
            for(int j = i ; j > k + 1; j--)
                arr[j] = arr[j-1];
            //插进去
            arr[k+1] = temp;
        }
        return arr;
    }
}

Summarize

Properties:
1. Time complexity: O(n2)
2. Space complexity: O(1)
3. Stable sorting
4. In-place sorting

Guess you like

Origin blog.csdn.net/BeanGo/article/details/132208175