标签:
class Program { /// <summary> /// 数组排序 /// </summary> /// <param name="arr">数组</param> /// <param name="b">true为从小到大排列 false为从大到小排列</param> /// <returns>排序完的数组</returns> static int[] Method(int[] arr,bool b)//方法一,先去确定后边,从后往前排 { for (int i = arr.Length - 1; i > 0; i--) { for (int j = 0; j < arr.Length - 1; j++) { if (arr[j] > arr[j + 1] && b)//小到大的判断 { int k = arr[j]; arr[j] = arr[j + 1]; arr[j + 1] = k; } if (arr[j] < arr[j + 1] && !b)//大到小的判断 { int k = arr[j]; arr[j] = arr[j + 1]; arr[j + 1] = k; } } } return arr; } /// <summary> /// 数组排序方法 /// </summary> /// <param name="arr">数组</param> /// <param name="b">true为从小到大排列 false为从大到小排列</param> /// <returns>排序完的数组</returns> static int[] Method2(int[] arr,bool b)//方法二,先确定前边数据,从前往后排 { for (int i = 0; i < arr.Length - 1;i ++) { for (int j = i ; j <= arr.Length - 1;j++) { if (arr[i] > arr[j] && b) { int k = arr[i]; arr[i] = arr[j]; arr[j] = k; } if (arr[i] < arr[j] && !b) { int k = arr[i]; arr[i] = arr[j]; arr[j] = k; } } } return arr; } static void Main(string[] args) { int[] arr = new int[18]; for (int i = 0;i <= 17;i ++) { Random rd = new Random(); Thread.Sleep(200); arr[i] = rd.Next(100); } foreach (int i in arr) Console.Write(i + " "); Console.Write("\n"); //利用方法一输出结果 Console.WriteLine ("方法一输出从小到大:"); arr = Method(arr,true); foreach (int i in arr) Console.Write(i + " "); Console.WriteLine("\n方法一输出从大到小:"); arr = Method(arr, false); foreach (int i in arr) Console.Write(i + " "); //利用方法二输出结果 Console.WriteLine("\n方法二输出从小到大:"); arr = Method2(arr,true); foreach (int i in arr) Console.Write(i + " "); Console.WriteLine("\n方法二输出从大到小:"); arr = Method2(arr, false); foreach (int i in arr) Console.Write(i + " "); Console.ReadLine(); } }
标签:
原文地址:http://www.cnblogs.com/whytohow/p/4726429.html