直接选择排序
直接选择排序,算法时间复杂度也是N^2, 其思想和冒泡有点相似,但是区别在于冒泡找到就交换,直接选择排序先找到位置最后在交换。
1class Program
2 {
3 static void Main(string[] args)
4 {
5 int[] a = { 7, 2, 1, 6, 21, 13, 8, 4, 33, 26 };
6 PrintArray(a);
7 SelectSort(a);
8 PrintArray(a);
9
10 }
11
12 private static void SelectSort(int[] array)
13 {
14 int k = 0;
15 for (int i = 0; i < array.Length; i++)
16 {
17 k = i;
18 for (int j = i + 1; j < array.Length; j++)
19 {
20 if (array[k] > array[j])
21 {
22 k = j;
23 }
24 }
25 if (i!=k)
26 {
27 int temp = array[i];
28 array[i] = array[k];
29 array[k] = temp;
30 }
31 }
32 }
33
34 private static void PrintArray(int[] array)
35 {
36 string result = string.Empty;
37 for (int i = 0; i < array.Length; i++)
38 {
39 result += array[i].ToString() + " ";
40 }
41 Console.WriteLine(result.Trim());
42 }
43 }
2 {
3 static void Main(string[] args)
4 {
5 int[] a = { 7, 2, 1, 6, 21, 13, 8, 4, 33, 26 };
6 PrintArray(a);
7 SelectSort(a);
8 PrintArray(a);
9
10 }
11
12 private static void SelectSort(int[] array)
13 {
14 int k = 0;
15 for (int i = 0; i < array.Length; i++)
16 {
17 k = i;
18 for (int j = i + 1; j < array.Length; j++)
19 {
20 if (array[k] > array[j])
21 {
22 k = j;
23 }
24 }
25 if (i!=k)
26 {
27 int temp = array[i];
28 array[i] = array[k];
29 array[k] = temp;
30 }
31 }
32 }
33
34 private static void PrintArray(int[] array)
35 {
36 string result = string.Empty;
37 for (int i = 0; i < array.Length; i++)
38 {
39 result += array[i].ToString() + " ";
40 }
41 Console.WriteLine(result.Trim());
42 }
43 }