您的位置:首页 > 其它

插入排序

2015-06-30 18:54 447 查看
插入排序

C++代码:

template <typename T>
void SortUtil<T>::insertionSort(vector<T>& data)
{
int j = 0;
for (int i = 1; i < data.size(); i++)
{
T key = data[i];

// insert data[i] into the sorted sequence data[0..i-1]
j = i;
while (j > 0 && data[j - 1] > key)
{
data[j] = data[j - 1];
j--;
}

data[j] = key;
}
}


测试代码(C++):

void display(vector<int> data)
{
for (auto& elem : data)
{
cout << elem << endl;
}
}

int main(int argc, char* argv[])
{
vector<int> data1 { 9, 5, 18, 21, 32, 93, 2 };
cout << "before sort:" << endl;
display(data1);
SortUtil<int>::insertionSort(data1);
cout << "after sort:" << endl;
display(data1);
}


运行结果:
before sort:
9
5
18
21
32
93
2
after sort:
2
5
9
18
21
32
93
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: