求:C#冒泡程序
要求:从键盘里输入数值
自从用了VS以后,渐渐地用记事本就写不出完整的代码了~~,所以只说下逻辑吧。
冒泡就是把一组数中,相邻两个的数比较大小,如果较小的数在前面,就把这两个数交换位置,否则不交换。经过一个嵌套循环,最后就可能把数字按从小到大,或从大到小排列好。
static void Main(string[] args) { int[] array = new int[] { 3, 4, 2, 1, 6, 5 }; Console.Write("排序前:"); for (int i = 0; i < array.Length;i++ ) Console.Write("array[{0}]={1} ", i, array[i]); sord1(array); Console.Write("排序后:"); for (int i = 0; i < array.Length; i++) Console.Write("array[{0}]={1} ", i, array[i]); array = new int[] { 3, 1, 2, 4, 6, 5 }; Console.Write("排序前:"); for (int i = 0; i < array.Length;i++ ) Console.Write("array[{0}]={1} ", i, array[i]); Console.WriteLine(); sord2(array); Console.Write("冒泡排序后:"); for (int i = 0; i < array.Length; i++) Console.Write("array[{0}]={1} ", i, array[i]); Console.ReadKey(); } //冒泡排序法 static void sord2(int[] array) { for (int i = 0; i < array.Length; i++) { Console.WriteLine(); Console.Write("第{0}轮排序:", i); for (int j = 0; j < array.Length - i - 1; j++) { if (array[j] < array[j + 1]) { int temp = array[j]; array[j] = array[j + 1]; array[j + 1] = temp; } Console.Write("array[{0}]={1} ", j, array[j]); } } Console.WriteLine(); } static void sord1(int[] array) { for (int i = 0; i < array.Length; i++) { Console.WriteLine(); Console.Write("第{0}轮排序:", i); for (int j = i; j < array.Length; j++) { if (array[i] < array[j]) { int temp = array[i]; array[i] = array[j]; array[j] = temp; } Console.Write("array[{0}]={1} ", j, array[j]); } }Console.WriteLine(); }