1 数据结构课程设计个人任务1:直接插入排序

先看这道题目的输入和输出

输入:

0
21 25 49 25 16 8

输出:

21 25 49 25 16 8 
21 25 49 25 16 8 
21 25 25 49 16 8 
16 21 25 25 49 8 
8 16 21 25 25 49 

排序过程如下

首先先设置一个变量t,指向数列第二个位置。
每次都从1到t-1进行遍历,如果A[t]比A[j]小可以插入j前部,就插入,否则不操作。

所以,就可以轻松写出代码(如下)。

#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <algorithm>
#include <cmath>
#include <cstring>
#include <vector>
#include <queue>
using namespace std;
template<class ElemType>
void SimpleInsertSort(vector<ElemType>& A)
{
	int i, j, k;
	int t;
	t = 1;
	if (A.size() == 0)
		return;
	if (A.size() == 1)
	{
		cout << A[0] << endl;
		return;
	}
	for (i = 0;i < A.size()-1; i++)
	{
		for (j = 0; j < t; j++)
		{
			if (A[t] <= A[j])
				break;
		}
		int temporary_p = j;
		ElemType temporary_num = A[t];
		for(j=t;j> temporary_p;j--)
			A[j] = A[j-1];
		A[temporary_p] = temporary_num;
		t++;
		for (k = 0; k < A.size(); k++)
			cout << A[k] << " ";
		cout << endl;
	}
}
int main()
{
	vector<int> input_int;
	vector<double> input_double;
	vector<char> input_char;
	vector<string> input_string;
	int kinds_num;
	cin >> kinds_num;
	if (kinds_num != 0 && kinds_num != 1 && kinds_num != 2 && kinds_num != 3)
	{
		cout << "err" << endl;
		return 0;
	}
	if (kinds_num == 0)
	{
		int temporary_int;
		while(cin>> temporary_int)
			input_int.push_back(temporary_int);
	}
	if (kinds_num == 1)
	{
		double temporary_double;
		while (cin >> temporary_double)
			input_double.push_back(temporary_double);
	}
	if (kinds_num == 2)
	{
		char temporary_char;
		while (cin >> temporary_char)
			input_char.push_back(temporary_char);
	}
	if (kinds_num == 3)
	{
		string temporary_string;
		while (cin >> temporary_string)
			input_string.push_back(temporary_string);
	}
	if (kinds_num == 0)
	{
		SimpleInsertSort(input_int);
	}
	if (kinds_num == 1)
	{
		SimpleInsertSort(input_double);
	}
	if (kinds_num == 2)
	{
		SimpleInsertSort(input_char);
	}
	if (kinds_num == 3)
	{
		SimpleInsertSort(input_string);
	}
	return 0;
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值