当前位置:主页 > 软件编程 > JAVA代码 >

java插入排序 Insert sort实例

时间:2020-10-25 09:40:12 | 栏目:JAVA代码 | 点击:

复制代码 代码如下:

     //直接插入排序
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;    //注意这里是j+1
    }
}

//折半插入排序
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])//这个判断可不要
        {
            low = 0;
            high = i-1;
            while (low <= high) //error: while( low < high) 注意这里还需要 等号
            {
                mid = (low+high)/2;
                if (temp < arr[mid])
                    high = mid - 1;
                else
                    low = mid + 1;
            }
            //经过上面的折半查找插入位置后,这时插入位置为low或者high+1,这时low等于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;
        }
    }
}  

您可能感兴趣的文章:

相关文章