Java Insert sort Insert sort instance

  • 2020-04-01 01:28:26
  • OfStack


     //Direct insertion sort
void DirectInsertionSort(int* arr, int nLen)
{
    int i, j;
    for (i=1; i<nLen; i++)
    {
        int temp = arr[i];
        for (j=i-1; j>=0; j--)
        {
            if (temp < arr[j])
                arr[j+1] = arr[j];
            else
                break;
        }
        if (j+1 != i)
            arr[j+1] = temp;    //Notice this is j plus 1
    }
}
//Half insertion sort
void BinaryInsertionSort(int* arr, int nLen)
{
    int i, j;
    int low, mid, high;
    for (i=1; i<nLen; i++)
    {
        int temp = arr[i];
        if (temp < arr[i-1])//Don't make that judgment
        {
            low = 0;
            high = i-1;
            while (low <= high) //Error: the while (low <Note that we also need an equal sign
            {
                mid = (low+high)/2;
                if (temp < arr[mid]) 
                    high = mid - 1;
                else 
                    low = mid + 1;
            }
            //After looking up the insertion position from the top half, the insertion position is either low or high+1, so low is equal to high+1
            //for (j=i-1; j>=high+1; j--)
            //{
            //    arr[j+1] = arr[j];
            //}
            //arr[high+1] = temp; 
            for (j=i-1; j>=low; j--) 
            {
                arr[j+1] = arr[j];
            }
            arr[low] = temp; 
        }
    }
}   


Related articles: