Moist - Practice Round China New Grad Test 2014 - 插入排序

Moist

题意:简单的字符串处理与插入排序。难度:1星。

从文件读取字符串数据之后,模拟插入排序过程,计算插入次数,再将计数输出到文件。

需要注意:

1)C++的文件操作;

2)从文件读取时,在读取了int型数据之后,如果要getline(),则需要在两句中间加上get()以吸收int数据后的换行符;

题解代码:

/*
 *	Moist - Practice Round China New Grad Test 2014
 *
 *	字符串处理与模拟插入排序过程;
 *
 */

#include <iostream>
#include <fstream>

using namespace std;

#define MAX_NAME_LENGTH 100
#define MAX_NAME_NUMBER 100

void InsertSort(char nameList[][MAX_NAME_LENGTH], int low, int high);

int main()
{
	ifstream inputFile;
	ofstream outputFile;
	int T, N, cnt;
	char nameList[MAX_NAME_NUMBER][MAX_NAME_LENGTH];
	int i, j;

	inputFile.open("E:\\C++\\GCJ\\China New Grad Test 2014\\Practice Round\\Moist\\C-small-practice-2.in");
	outputFile.open("E:\\C++\\GCJ\\China New Grad Test 2014\\Practice Round\\Moist\\C-small-practice-2.out");

	inputFile >> T;
	for (i = 0; i < T; i++)
	{
		inputFile >> N;
		inputFile.get();	/* 输入int型之后 && getline()之前,需要用get()吸收一个换行符 */
		for (j = 0; j < N; j++)
		{
			inputFile.getline(nameList[j], MAX_NAME_LENGTH);
		}

		for (j = 0, cnt = 0; j < N - 1; j++)
		{
			if (strcmp(nameList[j], nameList[j + 1]) > 0)
			{
				cnt++;
				InsertSort(nameList, 0, j + 1);
			}
		}//for (j = 0, cnt = 0; j < N - 1; j++)

		cout << cnt << endl;
		outputFile << "Case #" << i + 1 << ": " << cnt << endl;
	}//for (i = 0; i < T; i++)


	inputFile.close();
	outputFile.close();

	system("pause");
	return 0;
}

void InsertSort(char nameList[][MAX_NAME_LENGTH], int low, int high)
{	/* 升序插入排序 */
	/* nameList[low, high - 1][MAX_NAME_LENGTH]已有序,将nameList[high]插入 */
	while (high > low && strcmp(nameList[high], nameList[high - 1]) < 0)
	{
		char tmp[MAX_NAME_LENGTH];
		strcpy(tmp, nameList[high]);
		strcpy(nameList[high], nameList[high - 1]);
		strcpy(nameList[high - 1], tmp);
		high--;
	}
}



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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值