数组--选择排序

1、什么是选择排序:

  是指从尚未排序的各元素中选择最小的元素同第一个元素交换,再从剩余的元素中选择最小的元素与第二个元素交换,以此类推,直至最终完成排序。

 1 namespace ConsoleApplication1
 2 {
 3     class Program
 4     {
 5         static void bubble_sort(int[] unsorted)
 6          {
 7             //这一层for循环,决定接收变量(最后一个可不参加)
 8              for (int i = 0; i < unsorted.Length-1; i++)
 9              {
10                  int min=unsorted[i];//声明一个保存最小值的变量
11                  int minIndex = i;//声明一个保存最小值下标的变量
12 
13                  //这层循环,选择出数组中的最小值(所有元素都要参加比较)
14                  for (int j = i; j < unsorted.Length; j++)
15                  {
16                      if (unsorted[j] < min)
17                      {
18                          min = unsorted[j];
19                          minIndex = j;
20                      }
21                  }
22                  //最小值与下标为i的数组变量进行交换
23                  int temp = unsorted[i];
24                  unsorted[i] = min;
25                  unsorted[minIndex] = temp;
26              }
27          }
28  
29          static void Main(string[] args)
30          {
31              int[] x = { 6, 2, 4, 1, 5, 9,3 };//声明一个整型数组,并赋值
32              //冒泡前数组
33              Console.Write("排序前:");
34              foreach (var item in x)
35              {
36                  Console.Write(item+" ");
37               }
38              bubble_sort(x);//调用冒泡排序方法
39              //冒泡后数组
40              Console.Write("
排序后:");
41              foreach (var item in x)
42              {
43                  Console.Write(item+" ");
44              }
45              Console.ReadLine();
46          }
47     }
48 }
原文地址:https://www.cnblogs.com/pengyouqiang88/p/5023581.html