插入法的基本思想是:从第一个元素到第i个元素,假设已经排序好,然后将第i+1个元素按照大小顺序插入前i个元素中。
#pragma once
#include <iostream>
#include <vector>
#include "Test.h"
#include <stdlib.h>
#include<algorithm>
using std::cout;
using std::endl;
void Sort(double* dArr, int nSize)
{
if ( !dArr || nSize < 1)
return;
int i,j;
for ( i = 1; i < nSize; i++)
{
double dTemp = dArr[i];
for ( j = i; j > 0; j-- )<span style="white-space:pre"> </span>//将第i+1个元素按照顺序拆入到前面i个元素中(从后往前遍历)
{
if( dTemp < dArr[j-1] )<span style="white-space:pre"> </span>//若第i+1个元素比第j个元素小,则把j个到i个元素往后移动一个单位,直至第i+1个元素比第j个元素大
dArr[j] = dArr[j-1];
else
break;
}
dArr[j] = dTemp;
}
}
void main()
{
double* dArr = new double[10];
for ( int i = 0; i < 10; i++ )
{
dArr[i] = rand();
cout <<dArr[i]<<endl;
}
Sort(dArr,10);
for ( int i = 0; i < 10; i++ )
cout <<dArr[i]<<endl;
delete[] dArr;
system("pause");
}