直接插入排序(c++

#include 
#include 

using namespace std;

void InsertSort(vector& vec)
{
	int i;
	for (i = 0; i < vec.size() - 1; i++)
	{
		int temp = vec[i + 1];
		int j = i;
		while (j >= 0)
		{
			if (vec[j] >= temp)
			{
				vec[j + 1] = vec[j];
				j--;
			}
			else
				break;
		}
		vec[j + 1] = temp;
	}
}

void PrintArray(vector vec)
{
	for (int num : vec)
	{
		cout << num << " ";
	}
}

void Test()
{
	vector a;
	int n;
	while (cin >> n)
	{
		a.push_back(n);
	}
	InsertSort(a);
	PrintArray(a);
}

int main()
{
	Test();
	return 0;
}

你可能感兴趣的:(算法,数据结构)