很久没上博客园了,今天一口气把10月份的所有感兴趣的首页文章看完,看到一篇“让人懊恼的面试-看程序员的基本功 ”,说来巧啦,博主是我6个月前请教过的学长,当时刚接触.net,想做cms,而他正好在做一个开源的shangdongcms,因为当时刚接触,甚至想加入到那个项目中,结果邮件都写好了,却没发出去。
文章地址:http://www.cnblogs.com/soundbbg/archive/2008/10/31/1323971.html
面试的题目是:对字符串进行排序,用任意一种编程语言来实现,不能使用现有的类,在排序中,字符串“Bc”,“Ad”,“aC”,“Hello”,“X man”,“little”,“During”,“day”能够排序成“Ad”,"aC",“Bc”,“During”,“day”,“Hello”,“little”,“x man”,也就是说,在排序的过程并不是传统的按照字符串排序,在排序中还需要将小写字母一并排序,也就是说a字符串要在B或b之前。
当时想了想,晚上才开始写代码:
首先用冒泡排序,调用String的CompareTo试验了一下:
Code
public void StringSort()
{
bool exchange;
for (int i=0; i < to_be_sort.Length-1; i++)
{
exchange = false;
for (int j = to_be_sort.Length - 2; j >= i; j--)
{
if (to_be_sort[j].CompareTo(to_be_sort[j+1]))
{
singleStr = to_be_sort[j + 1];
to_be_sort[j + 1] = to_be_sort[j];
to_be_sort[j] = singleStr;
exchange = true;
}
}
if (!exchange)
{
break;
}
}
}
结果如图:
小a跑前面去了,用Reflector反汇编看下CompareTo也没看出什么。
大致整理了下思路,冒泡一次,然后传两个字符串进去比较。
private int SingleStrSort(string str1,string str2)
{
}
比较的时候,如果首字母相同,要求比较下一个字符
因为要对大、小写进行比较于是写了个大小写转换方法:
private char JudgeChar(char chr)
{
}
StringSort类:
Sort类:
Code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace InterviewPromble.StringSort
{
class Sort
{
private string[] to_be_sort;
// private string[] sorted;
private string singleStr;
public Sort(string[] str)
{
to_be_sort = str;
}
public void Get_to_be_sort()
{
for (int i = 0; i < to_be_sort.Length; i++)
{
Console.WriteLine(to_be_sort[i]);
}
}
public void StringSort()
{
bool exchange;
for (int i=0; i < to_be_sort.Length-1; i++)
{
exchange = false;
for (int j = to_be_sort.Length - 2; j >= i; j--)
{
if (SingleStrSort(to_be_sort[j],to_be_sort[j+1])>0)
{
singleStr = to_be_sort[j + 1];
to_be_sort[j + 1] = to_be_sort[j];
to_be_sort[j] = singleStr;
exchange = true;
}
}
if (!exchange)
{
break;
}
}
}
private int SingleStrSort(string str1,string str2)
{
int length;
int k=0;
if (str1.Length >= str2.Length)
length = str1.Length;
else
length = str1.Length;
while (k < length)
{
if (JudgeChar(str1[k]) > JudgeChar(str2[k]))
return 1;
else if (JudgeChar(str1[k]) < JudgeChar(str2[k]))
return -1;
else if(JudgeChar(str1[k]) == JudgeChar(str2[k]))
{
if(str1[k]>str2[k])
{
return 1;
}
else
return -1;
}
else
k++;
}
return 0;
}
private char JudgeChar(char chr)
{
if (chr > 'Z')
return chr -= (char)('a' - 'A');
else
return chr;
}
}
}
写完后运行没问题,马上跑去看学长的实现代码,感觉思路是一样的。后来又请教了Gray Zhang ,发现有更好的办法。
继续研究。。。。。
Code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace InterviewPromble.StringSort
{
class Program
{
public static void Main(string[] arg)
{
string[] sortString ={ "Bc","Ad","aC","Hello","X man","little","During","day"};
Sort sort = new Sort(sortString);
sort.StringSort();
sort.Get_to_be_sort();
Console.ReadLine();
}
}