1 //冒泡排序 把一个数组里面的数从大到小排列 2 int[] nums = new int[7] { 7, 6, 8, 5, 1, 9, 4 }; 3 int temp; 4 //外循环每次把参与排序的最大数排在最后 5 for (int i = 1; i <= 6; i++)//每个数i要比几遍(第一个数比6遍,第二个数比5遍,...),即次数 6 { 7 //内层循环负责对比相邻的两个数,并把最大的排在后面 8 for (int j = 1; j <= 7 - i; j++)//7-i为趟数 9 { 10 if (nums[j] < nums[j - 1]) 11 { 12 temp = nums[j]; 13 nums[j] = nums[j - 1]; 14 nums[j - 1] = temp; 15 } 16 } 17 } 18 for (int i = 0; i < 7; i++) 19 { 20 Console.WriteLine(nums[i]); 21 }
1 //非冒泡排序 分数由高到低排序 2 int[] players = new int[7] { 7, 6, 8, 5, 1, 9, 4 }; 3 int temp; 4 for (int i = 0; i < players.Length; i++) 5 { 6 //j表示从i+1开始后面的数 7 for (int j = i + 1; j < players.Length; j++)//j先与i+1比较,再与数组剩余的数比较 8 { 9 if (players[i] < players[j]) 10 { 11 //把两个数交换 12 temp = players[i]; 13 players[i] = players[j]; 14 players[j] = temp; 15 } 16 } 17 } 18 //打印数组 19 for (int i = 0; i < players.Length; i++) 20 { 21 Console.Write(players[i] + " "); 22 }
时间: 2024-10-06 15:48:39