好记性不如烂笔头:
(1)冒泡排序
基本冒泡排序代码
int[] numbers = { 5,2,6,7,3}; int temp = 0; for (int i = 0; i < numbers.Length-1;i ++ ) { for (int j = 0; j < numbers.Length - 1 - i; j ++) { if (numbers[j ]>numbers [j+1 ]) { temp =numbers [j ]; numbers[j] = numbers[j + 1]; numbers[j + 1] = temp; } } } for (int ii = 0; ii < numbers.Length-1;ii ++ ) { Console.WriteLine(numbers [ii ].ToString ()); } Console.ReadKey();
冒泡排序优化
int[] numbers = { 5,2,6,7,3}; int temp = 0; int flag ; for (int i = 0; i < numbers.Length-1;i ++ ) { flag = 1; for (int j = 0; j < numbers.Length - 1 - i; j ++) { if (numbers[j ]>numbers [j+1 ]) { flag = 0; temp =numbers [j ]; numbers[j] = numbers[j + 1]; numbers[j + 1] = temp; } } if (flag == 1) break; } for (int ii = 0; ii < numbers.Length-1;ii ++ ) { Console.WriteLine(numbers [ii ].ToString ()); } Console.ReadKey();
(2)选择排序
选择排序代码
int[] numbers = { 105,120,10,200,20}; int temp = 0; int minIndex = 0; for (int i = 0; i < numbers.Length ; i++) { minIndex = i; for (int j = i; j < numbers.Length; j++) { //注意这里比较的是numbers[minIndex] if (numbers[j] < numbers[minIndex]) { minIndex = j; } } temp = numbers[minIndex]; numbers[minIndex] = numbers[i]; numbers[i] = temp; for (int ii = 0; ii < numbers.Length - 1; ii++) { Console.WriteLine(numbers[ii].ToString()); } Console.ReadKey();
(3)插入排序算法
插入算法代码
int[] numbers = { 70,80,30,10,20}; for (int i = 1; i < numbers.Length; i++) { int t = numbers[i]; int j = i; while ((j > 0) && (numbers[j - 1] > t)) { numbers[j] = numbers[j - 1];//交换顺序 --j; } numbers[j] = t; } for (int ii = 0; ii < numbers.Length - 1; ii++) { Console.WriteLine(numbers[ii].ToString()); } Console.ReadKey();