详解三种C#实现数组反转方式
今天上班中午吃饱之后、逛博客溜达看到一道题:数组反转 晚上回家洗完澡没事情做,就自己练习一把。
publicstaticclassArrayReserve { //////使用Array.Reverse(Arrar)反转全部 /// ///publicstaticvoidReverseDemo1(int[]arr) { Console.WriteLine("使用Array.Reverse(Arrar)反转全部"); Array.Reverse(arr); } /// ///使用Array.Reverse(Arrayarr,intbegin,intend),反转指定部分 /// ////// /// publicstaticvoidReverseDemo2(int[]arr,intbegin,intend) { Console.WriteLine("使用Array.Reverse(Arrayarr,intbegin,intend),反转指定部分"); Array.Reverse(arr,begin,end); } /// ///使用自定义方法实现反转 /// ////// /// publicstaticvoidReverseDemo3(int[]arr,intbegin,intend) { Console.WriteLine("使用自定义方法实现反转"); if(null==arr) { thrownewArgumentNullException("arr","Array不能为null"); } if(begin<=0||end<=0) { thrownewArgumentOutOfRangeException("开始或结束索引没有正确设置"); } if(end>arr.Length) { thrownewArgumentOutOfRangeException("end","结束索引超出数组长度"); } while(begin ///使用自定义方法实现反转(使用栈《后进先出》) /// /// /// /// publicstaticvoidReverseDemo4(int[]arr,intbegin,intend) { Console.WriteLine("使用自定义方法实现反转(使用栈《后进先出》)"); if(null==arr) { thrownewArgumentNullException("arr","Array不能为null"); } if(begin<=0||end<=0) { thrownewArgumentOutOfRangeException("开始或结束索引没有正确设置"); } if(end>arr.Length) { thrownewArgumentOutOfRangeException("end","结束索引超出数组长度"); } Stack intStack=newStack (); inttempBegin=begin; for(;begin<=end;begin++) { intStack.Push(arr[begin]); } for(;tempBegin<=end;tempBegin++) { arr[tempBegin]=intStack.Pop(); } } }
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。