将数组里的数字进行排序的几种方法
1、冒泡排序
Console.WriteLine("\n冒泡排序"); int[] arr = new int[5] { 2, 5, 8, 4, 0 }; for (int k = 0; k < arr.Length; k++) { for (int j = 0; j < arr.Length - 1; j++) { for (int i = 0; i < arr.Length - 1 - j; i++) { if (arr[i] > arr[i + 1]) { int temp1 = arr[i]; arr[i] = arr[i + 1]; arr[i + 1] = temp1; } } } Console.Write(" " + arr[k]); }
2、选择排序
Console.WriteLine("\n选择排序"); int[] arr2 = { 2, 5, 8, 4, 0 }; for (int j = 0; j < arr2.Length; j++) { int minNum = arr2[j], minIndex = j; for (int i = j; i < arr2.Length; i++) { if (arr2[i] < minNum) { minNum = arr2[i]; minIndex = i; } int temp1 = arr2[j]; arr2[j] = arr2[minIndex]; arr2[minIndex] = temp1; } } for (int i = 0; i < arr2.Length; i++) { Console.Write(" " + arr2[i]); }
3、按照扑克牌顺序排序(2最大,1第二大,3~13依次排)
要求:把数字放进一个ArrayList数组,1~13数字不能重复,写一个方法来排序。
class Program { static void Main(string[] args) { Random r = new Random(); ArrayList al = new ArrayList(); int k = 0; do { k = r.Next(1, 14); if (!al.Contains(k)) { al.Add(k); } } while (al.Count < 13); //随机数字放进数组 Console.WriteLine("排序前"); foreach (object item in al) { Console.Write(" " + item); } Sort(al); } public static void Sort(ArrayList al) { Console.WriteLine("\n升序排序后"); for (int j = 0; j < al.Count - 1; j++) { for (int i = 0; i < al.Count - 1 - j; i++) { if (Collation((int)al[i],(int)al[i + 1])) //调Collation用方法进行排序,这里是升序;如果要降序,把参数互换即可 { int temp = (int)al[i]; al[i] = (int)al[i + 1]; al[i + 1] = temp; } } } //冒泡排序 for (int i = 0; i < al.Count; i++) { Console.Write(" " + al[i]); } } public static bool Collation(int a,int b) //collation 排序规则 { if (a == 2) { return true; } else if (b == 2) { return false; } else if (a == 1) { return true; } else if(b == 1) { return false; } return a > b; } //按要求逐层排序 }