C#常見演算法題目(面試準備)
阿新 • • 發佈:2019-02-19
1.寫出冒泡,選擇,插入排序演算法。
//氣泡排序publicclass bubblesorter
{
publicvoid sort(int[] list)
{
int i, j, temp;
bool done =false;
j =1;
while ((j < list.Length) && (!done))
{
done =true;
for (i
{
if (list[i] > list[i +1])
{
done =false;
temp = list[i];
list[i] = list[i +1];
list[i +1] = temp;
}
}
j++;
}
}
}
//選擇排序
publicclass selectionsorter
{
privateint min;
publicvoid sort(int[] list)
{
for (int i =0; i < list.Length -1; i++)
{
min = i;
for (int j
{
if (list[j] < list[min])
min = j;
}
int t = list[min];
list[min] = list[i];
list[i] = t;
}
}
}
//插入排序
publicclass insertionsorter
{
publicvoid sort(int[] list)
{
for (int i =1; i < list.Length; i++)
{
int t = list[i];
int j = i;
while ((j >0) && (list[j -1] > t))
{
list[j] = list[j -1];
--j;
}
list[j] = t;
}
}
}
2.有一列數1,1,2,3,5,........求第30個數.
publicclass MainClass{
publicstaticvoid Main()
{
Console.WriteLine(Foo(30));
}
publicstaticint Foo(int i)
{
if (i <=0)
return0;
elseif (i >0&& i <=2)
return1;
elsereturn Foo(i -1) + Foo(i -2);
}
}
3. 程式設計: 貓大叫一聲,所有的老鼠都開始逃跑,主人被驚醒。
publicdelegatevoid SubEventHandler();publicabstractclass Subject
{
publicevent SubEventHandler SubEvent;
protectedvoid FireAway()
{
if (this.SubEvent !=null)
this.SubEvent();
}
}
publicclass Cat : Subject
{
publicvoid Cry()
{
Console.WriteLine(cat cryed.);
this.FireAway();
}
}
publicabstractclass Observer
{
public Observer(Subject sub)
{
sub.SubEvent +=new SubEventHandler(Response);
}
publicabstractvoid Response();
}
publicclass Mouse : Observer
{
privatestring name;
public Mouse(string name, Subject sub) : base(sub)
{
this.name = name;
}
publicoverridevoid Response()
{
Console.WriteLine(name + attempt to escape!);
}
}
publicclass Master : Observer
{
public Master(Subject sub) : base(sub){}
publicoverridevoid Response()
{
Console.WriteLine(host waken);
}
}
class Class1
{
staticvoid Main(string[] args)
{
Cat cat =new Cat();
Mouse mouse1 =new Mouse(mouse1, cat);
Mouse mouse2 =new Mouse(mouse2, cat);
Master master =new Master(cat);
cat.Cry();
}
}
4.有一個字串 "I am a good man",設計一個函式,返回 "man good a am I"。
5.A、B、C、D、E五名學生有可能參加計算機競賽,根據下列條件判斷哪些
人蔘加了競賽:
(1)A參加時,B也參加;
(2)B和C只有一個人參加;
(3)C和D或者都參加,或者都不參加;
(4)D和E中至少有一個人參加;
(5)如果E參加,那麼A和D也都參加。
{
char[] name={'A','B','C','D','E'};
int[] value =newint[5];
for (value[0]=0;value[0]<2;value [0]++)
for (value[1]=0; value[1] <2; value[1]++)
for (value[2]=0; value[2] <2; value[2]++)
for (value[3]=0; value[3] <2; value[3]++)
for (value[4]=0; value[4] <2; value[4]++)
{
if ((value[1] >= value[0]) && (value[1] + value[2] ==1) &&