Sorting Algorithm Exercise-Insert Sort

Introduction

Insert sorting is a sorting algorithm with time complexity of O (n 2 ) level. So why do we have to learn algorithms with O (n 2 ) time complexity ? In some cases, insertion sort is faster, for example, for a near-ordered array or when the fluctuation range of element values ​​is relatively small, insertion sort has natural advantages. The idea of ​​insertion sorting can also be applied to higher-level algorithms, which can help us further optimize sorting.

Specific ideas

  • Set an index value i to index to the position of the second element.
  • Set another index value j so that j = i . Then let the element indexed by the current j be compared with the previous element, and if it does not meet the order that needs to be scheduled, exchange it until the requirement that the order needs to be scheduled is met.
  • And so on, until all the following elements are traversed.

Code

The following uses C ++ to implement a basic insertion sort algorithm:

#include<bits/stdc++.h>
using namespace std;

template<class T>
void insertionSort(T arr[], int n) {
    //从第二个元素开始
    for(int i = 1; i < n; i++) {
        for(int j = i; j > 0; j--) {
            //依次与前一个元素比较
            if(arr[j-1] > arr[j]) 
                swap(arr[j-1], arr[j]);
        }
    }
    return;
}

int main(int argc, char const *argv[])
{
    // 测试
    int arr[10] = {10, 9, 8, 7, 6, 5, 4, 3, 2, 1};
    insertionSort(arr, 10);
    for(int i = 0; i < 10; i++) {
        printf("%d ", arr[i]);
    }
    return 0;
}

optimization

Many times we need to optimize our code, the above code can also be optimized. This is an optimized insertion sort I wrote.

#include<bits/stdc++.h>
using namespace std;

template<class T>
void insertionSortAd(T arr[], int n) {
    //从第二个元素开始
    for(int i = 1; i < n; i++) {
        //备份当前值
        T temp = arr[i];
        int j;
        for(j = i; j > 0 && arr[j-1] > temp; j--) {
            //当前面的元素不满足排序要求,覆盖到后面的位置,直到满足排序要求
            arr[j] = arr[j-1];
        }
        //此时 j 所在的位置就是temp该在的位置
        arr[j] = temp;
    }
    return;
}

int main(int argc, char const *argv[])
{
    // 测试
    int arr[10] = {10, 9, 8, 7, 6, 5, 4, 3, 2, 1};
    insertionSortAd(arr, 10);
    for(int i = 0; i < 10; i++) {
        printf("%d ", arr[i]);
    }
    return 0;
}

The impact of frequent exchanges on time is eliminated.

At last

  • Due to the limited level of bloggers, there are inevitable omissions, readers are welcome to criticize and correct!
Published 5 original articles · Liked4 · Visits 152

Guess you like

Origin blog.csdn.net/weixin_43587255/article/details/105505666