去哪儿网2014校园招聘技术笔试题(成都站,开发岗)——2014.09.23

已知字母序列【d, g, e, c, f, b, o, a】,请实现一个函数针对输入的一组字符串 input[] = {"bed", "dog", "dear", "eye"},按照字母顺序排序并打印。

本例的输出顺序为:dear, dog, eye, bed。


// test71.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include<iostream>
#include<string>
using namespace std;

int pos(char *seq, char c)
{
	for(int i = 0 ; i < strlen(seq);i ++)
		if(seq[i] == c)
			return i;
	return -1;
}

bool bigger(char *seq, string s1, string s2)
{
	int len1 = s1.length();
	int len2 = s2.length();
	int i = 0 ;
	while( i < len1 && i < len2)
	{
		int pos1 = pos(seq,s1[i]);
		int pos2 = pos(seq,s2[i]);
		i ++;
		if(pos1 < pos2)
			return true;
		else if(pos1 > pos2)
			return false;
		else
			continue;
	}

	if(i < len1)
		return true;
	else
		return false;
}

void swap(string & s1, string & s2)
{
	string c = s1;
	s1 = s2;
	s2 = c;
}

void Sort(char * seq, string * s , int n)
{
	int len = n;
	if(len == 1)
		return ;
	bool change = false;
	for(int i = 0 ; i < len - 1 ; i ++)
	{
		for(int j = 0 ; j < len - 1 - i ; j ++)
		if(! bigger(seq , s[j] , s[j + 1]))
		{
			swap(s[j] , s[j + 1]);
			change = true;
		}
		if(! change)
			break;
	}

}

int main(int argc, char* argv[])
{
	char seq[] = {'d','g','e','c','f','b','o','a'};
    string s[] = {"bed","dog","dear","eye"};

	Sort(seq,s,4);

	for(int i = 0 ; i < 4; i ++)
		cout<<s[i]<<"    ";

	

	return 0;
}

你可能感兴趣的:(去哪儿网2014校园招聘技术笔试题(成都站,开发岗)——2014.09.23)