最近做的东西总是感觉到运行慢,开始重新学习数据结构和算法,以提高程序性能!!!
下面是一个排序的类,用了几种方式实现的。
1using System;
2
3namespace DataStruct
4{
5 public class Sorter
6 {
7 /**//// <summary>
8 /// 冒泡排序法1
9 /// </summary>
10 /// <param name="list"></param>
11 public static void BubbleSort(int list)
12 {
13 for (int i = 0; i < list.Length; i++)
14 {
15 for (int j = i; j < list.Length; j++)
16 {
17 if (list[i] < list[j])
18 {
19 int temp = list[i];
20 list[i] = list[j];
21 list[j] = temp;
22 }
23 }
24 }
25 }
26
27 /**//// <summary>
28 /// 插入排序法
29 /// </summary>
30 /// <param name="list"></param>
31 public static void InsertionSort(int list)
32 {
33 for (int i = 1; i < list.Length; i++)
34 {
35 int t = list[i];
36 int j = i;
37 while ((j > 0) && (list[j - 1] > t))
38 {
39 list[j] = list[j - 1];
40 --j;
41 }
42 list[j] = t;
43 }
44
45 }
46
47 /**//// <summary>
48 /// 选择排序法
49 /// </summary>
50 /// <param name="list"></param>
51 public static void SelectionSort(int list)
52 {
53 int min;
54 for (int i = 0; i < list.Length - 1; i++)
55 {
56 min = i;
57 for (int j = i + 1; j < list.Length; j++)
58 {
59 if (list[j] < list[min])
60 min = j;
61 }
62 int t = list[min];
63 list[min] = list[i];
64 list[i] = t;
65 }
66
67 }
68
69 /**//// <summary>
70 /// 希尔排序法
71 /// </summary>
72 /// <param name="list"></param>
73 public static void ShellSort(int list)
74 {
75 int inc;
76 for (inc = 1; inc <= list.Length / 9; inc = 3 * inc + 1) ;
77 for (; inc > 0; inc /= 3)
78 {
79 for (int i = inc + 1; i <= list.Length; i += inc)
80 {
81 int t = list[i - 1];
82 int j = i;
83 while ((j > inc) && (list[j - inc - 1] > t))
84 {
85 list[j - 1] = list[j - inc - 1];
86 j -= inc;
87 }
88 list[j - 1] = t;