• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
gooliugle
博客园    首页    新随笔    联系   管理    订阅  订阅
数据结构与算法读书笔记2----C# 选择排序

C# 选择排序

代码
 1 using System;
 2 using System.Collections.Generic;
 3 using System.Text;
 4 
 5 namespace BubbleSort
 6 {
 7     class Program
 8     {
 9         static void Main(string[] args)
10         {
11             TestArray nums = new TestArray(10);
12             #region  初始化数组
13             Random rnd = new Random(100);
14             for (int num = 0; num < 10; num++)
15             {
16                 nums.Insert(rnd.Next(0,100));
17             }
18             #endregion
19             Console.WriteLine("Before Sorting: ");
20             nums.DisplayElements();
21             Console.WriteLine("Durring Sorting: ");
22             nums.SelectionSort();
23             Console.WriteLine("After Sorting: ");
24             nums.DisplayElements();
25             Console.ReadLine();
26         }
27     }
28 }
29 public class TestArray
30 {
31     private int[] arr;
32     private int upper;
33     private int numElements;
34     public TestArray(int size)
35     {
36         arr = new int[size];
37         upper = size - 1;
38         numElements = 0;
39     }
40     public void Insert(int item)
41     {
42         arr[numElements] = item;
43         numElements++;
44     }
45     public void DisplayElements()
46     {
47         for (int num = 0; num <= upper; num++)
48         {
49             Console.Write(arr[num]+" ");
50         }
51         Console.WriteLine();
52     }
53     public void Clear()
54     {
55         for (int num = 0; num <= upper; num++)
56         {
57             arr[num] = 0;
58         }
59         numElements = 0;
60     }
61     //选择排序算法
62     public void SelectionSort()
63     {
64         int min,temp;
65         for (int outer = 0; outer <= upper; outer++)
66         {
67             min = outer;
68             for (int inner = outer + 1; inner <= upper; inner++)
69             {
70                 if (arr[inner] < arr[min])
71                 {
72                     min = inner;
73                 }
74             }
75             temp = arr[outer];
76             arr[outer]=arr[min];
77             arr[min] = temp;
78             this.DisplayElements();
79         }
80 
81     }
82 } 

 

 

posted on 2010-04-20 21:43  gooliugle  阅读(253)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3