Sorting Algorithms - Insertion Sort

Insert sequencing method: The recording element is inserted, with the front element size comparison, the query to the insertion position, then it is larger than the element then moves back to the empty position of the insertion, the inserted element.

The remaining steps ② and the same. . .

Here are three kinds of codes, from the base to optimize

//1
void InsertSort(int* a, int n)
{
    for (int i = 1; i < n; ++i)
    {
        if (a[i] < a[i - 1])
        {
            int temp = a[i];
            for (int j = 0; j < i; ++j)
            {
                if (temp < a[j])
                {
                    for (int k = i; k > j; k--)
                        a[k] = a[k - 1];
                    a[j] = temp;
                    break;
                }
            }
        }
    }
}
//2
void InsertSort(int* a, int n)
{
    int i, j;
    for ( i = 1; i < n; i++)
    {
        if (a[i] < a[i - 1])
        {
            int temp = a[i];
            for (j = i; j >= 0 && a[j-1] > temp; j--)
            {
                a[j] = a[j - 1];
            }
            a[j] = temp;
        }
    }
}
//3
void
InsertSort(int* a, int n) { int temp; for (int i = 1; i < n; i++) { int low = 0, high = i - 1; temp = a[i]; while (low <= high) { int mid = (low + high) / 2; if (temp < a[mid]) high = mid - 1; else low = mid + 1; } for (int j = i; j > low; --j) { a[j] = a[j - 1]; } a[low] = temp; } }

Main methods:

int main()
{
    int arr[] = { 9,2,3,1,5,4,7,8,6 };
    int n = sizeof(arr) / sizeof(int);

    InsertSort(arr, n); //插入排序

    for (int i = 0; i < n; i++)
    {
        cout << arr[i] << " ";
    }
    cout << endl;
    return 0;
}

 

Guess you like

Origin www.cnblogs.com/single-dont/p/11354265.html