int l;再在循环多次使用l。比在循环里多次重复定义l速度快。
重复多次调用aa.bb.cc.dd。不如先保存cc。然后再多次调用cc.dd效率高。这个其实取决于有没有返回新的副本。
一:泛型编程
class Node
{
public T data;
public Node next;
public Node(T t,Node _next)
{
data = t;
next = _next;
}
}
二:系统时间测试
namespace TimeTest
{
class SystemTimeTest
{
static public void Main()
{
int[] i=new int[50000];
double t=0;
double t2 = 0;
DateTime startTime= DateTime.Now;
BuildArray(i);
t = DateTime.Now.Subtract(startTime).TotalSeconds;//获取总秒数
Console.WriteLine("构建数组时间:" + t);
startTime = DateTime.Now;
Run(i);
t2 = DateTime.Now.Subtract(startTime).TotalSeconds;//获取总秒数
Console.WriteLine("遍历数组时间:" + t2);
// t = t2 + t;
Console.WriteLine("总时长:" + (t+t2));
}
static void BuildArray(int[] arr)
{
for (int i = 0; i < arr.GetUpperBound(0);i++ )
{
arr[i] = i;
}
}
static void Run(int[] arr)
{
for(int i=0;i
根据进程运行时间:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Diagnostics;//诊断
namespace TimeTest
{
class SystemTimeTest
{
static int[] a = new int[10000];
static public void Main()
{
BuildArray(a);
double[] d=new double[4];
string[] s=new string[4];
TimeSpan startTime=new TimeSpan(0), endTime=new TimeSpan(0);
GC.Collect();
GC.WaitForPendingFinalizers();//挂起当前进程,等待垃圾回收完。(等待期间完成)
for (int i = 0; i < d.Length;i++ )
{
startTime = Process.GetCurrentProcess().Threads[0].UserProcessorTime;
s[i] = Run(i+1);
endTime = Process.GetCurrentProcess().Threads[0].UserProcessorTime;
d[i] = endTime.Subtract(startTime).TotalSeconds;
}
Console.WriteLine();
for(int i=0;i
三、1:静态数组
static void Main(string[] args)
{
string[] names;
names = new string[5];
//实例化数组
string[] names2 = new string[5];
int[] numbers=new int[] {1,2,3,4,5};
Console.WriteLine( names.GetLength(0));//5(个数)
Console.WriteLine(names.GetUpperBound(0));//4(最大元素)
Type t = numbers.GetType();
t.IsArray;//是否是数组
}
void sumNums(params int[] num)//变形参数函数
{
}
static void Main(string[] args)
{
CArray ca = new CArray(10);
Random rd=new Random(100);
for(int i=0;i<20;i++)
{
ca.Insert(rd.Next(0,100));
}
ca.PrintAll();
ca.BubbleSort(true);
ca.PrintAll();
}
}
class CArray
{
int[] arr;
private int upper;
private int count;
public int Upper { get { return upper; } }
public int Count { get { return count; } }
private int currEme = 0;
public CArray(int size)
{
arr = new int[size];
upper = size - 1;
count = size;
}
public bool Insert(int value)
{
if (currEme <= upper)
{
arr[currEme] = value;
currEme++;
return true;
}
else
{
return false;
}
}
public void PrintAll()
{
for(int i=0;i b)
{
temp = a;
a = b;//获取比较小的k
b = temp;//k变成比较大的i
}
}
}
选择排序://较快 数量越多 速度按倍数变慢
public void SelectionSort(bool big)//选择排序,是否按大小排序
{
int min;
int temp;
for (int i = 0; i < count; i++)
{
min = i;
for (int k = i + 1; k < count; k++)
{
if (big)
{
if (arr[min] < arr[k]) min = k;//前面的小于后面的才换。
}
else if (arr[min] > arr[k]) min = k;//前面的大于后面的才换
}
temp = arr[i];
arr[i] = arr[min];
arr[min] = temp;
}
}
public int CustomSearch(int value)
{
int sIndex=-1;
for(int i=0;icount*0.2)//如果查找的位置大于总数的百分之20.就向前移动一下。
{
int temp = arr[sIndex-1];//拿到上一个元素的值
arr[sIndex - 1] = arr[sIndex];//找到的值和上一个元素交换
arr[sIndex] = temp;
sIndex--;//返回上一个元素索引
}
return sIndex;
}
}
return sIndex;
}
public int binSearch(int value)
{
int upperBound=upper, loserBound=0, mid;
while (upperBound >= loserBound)
{
mid = (upperBound + loserBound) / 2;
if (value == arr[mid])
return mid;
if (value > arr[mid]) loserBound = mid+1;
else
upperBound = mid-1;
}
return -1;
}
五、1:栈的简单使用
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Collections;
using System.Text.RegularExpressions;//正则表达式
namespace ConsoleApplication7
{
class Program
{
static void Main(string[] args)
{
string expression = "5 + 10 + 15 + 20 - 1";
Stack nums = new Stack();
Stack ops = new Stack();
Calulate(nums, ops, expression);
Console.WriteLine(nums.Pop().ToString());
}
static bool IsNumberic(string input)
{
bool flag = true;
string pattern = @"^\d+$";
Regex validate = new Regex(pattern);
if (!validate.IsMatch(input))
flag = false;
return flag;
}
static void Calulate(Stack N, Stack O, string exp)
{
string ch, token = "";
for (int i = 0; i < exp.Length; i++)
{
ch = exp.Substring(i, 1);
if (IsNumberic(ch))
token += ch;
if (ch == " " || i == (exp.Length - 1))
{
if (IsNumberic(token))
{
N.Push(token);
token = "";
}
}
else if (ch == "+" || ch == "-")
O.Push(ch);
if (N.Count == 2)
Compute(N, O);
}
}
static void Compute(Stack N,Stack O)
{
int oper1, oper2;
string oper;
oper1 = Convert.ToInt32( N.Pop());
oper2 = Convert.ToInt32(N.Pop());
oper = O.Pop().ToString();
switch(oper)
{
case "+":
N.Push(oper1 + oper2);
break;
case "-":
N.Push(oper2 - oper1);
break;
}
}
}
}
static void MulBase(int n,int b)
{
Stack Digits=new Stack();
do
{
Digits.Push(n % b);
n = n / b;
}
while (n > 0);
while(Digits.Count>0)
{
Console.Write(Digits.Pop());
}
}
正常表达式:
class Program
{
static void Main(string[] args)
{
Regex reg = new Regex("thea");
string str1 = "aaatheaaatheaa";
Match matchSet = reg.Match(str1);
if(matchSet.Success)
{
Console.WriteLine("找到的位置:" + matchSet.Index);
}
MatchCollection result = reg.Matches(str1);//多个结果
if(result.Count>0)
{
foreach(Match m in result)
{
Console.WriteLine("2找到的位置:" +m.Index );
}
}
string[] words = new string[] { "bad", "bd", "baaad", "bear", "bend" };
foreach(string word in words)
{
if (Regex.IsMatch(word, "ba+"))//a至少出现一次
Console.Write(word + " ");
}
Console.WriteLine();
foreach (string word in words)
{
if (Regex.IsMatch(word, "ba*"))//a可以出现任意次数(可以没有)
Console.Write(word + " ");
}
Console.WriteLine();
foreach (string word in words)
{
if (Regex.IsMatch(word, "ba?d"))//a最多出现一次(可以没有)bad或bd
Console.Write(word + " ");
}
Console.WriteLine();
Console.WriteLine("============================");
string[] ds = new string[] { "Part", "of", "this", "string", "bold" };
string regExp = "<.*?>";//<.*>贪心。<.*?>惰性
MatchCollection mc;
foreach(string word in ds)
{
if(Regex.IsMatch(word,regExp))//如果匹配到了
{
mc = Regex.Matches(word, regExp);
for(int i=0;i
//b 匹配单词边界的位置
//| 是或的意思
} }
十一:1、.net自带的双向链表
static void Main(string[] args)
{
LinkedListNode node1 = new LinkedListNode("字符串值");
LinkedList names = new LinkedList();
names.AddFirst(node1);
LinkedListNode node2=new LinkedListNode("Node2");
names.AddAfter(node1, node2);
names.AddAfter(node1, "传对象");
LinkedListNode node3 = new LinkedListNode("第三、四");
names.AddAfter(node2, node3);
LinkedListNode aNode = names.First;
for(;aNode!=null;aNode=aNode.Next)//遍历
{
Console.WriteLine(aNode.Value);
}
Console.WriteLine("======查找========");
aNode = names.Find("Node2");//查找
if(aNode!=null)
Console.WriteLine(aNode.Value);
}
十二:二叉搜索树BinarySearchTree
class Node
{
public int Data;
public Node Left;
public Node Right;
public void DisplayNode()
{
Console.Write(Data + " ");
}
}
class BinarySearchTree
{
static void Main()
{
BinarySearchTree nums = new BinarySearchTree();
nums.Insert(23);
nums.Insert(45);
nums.Insert(16);
nums.Insert(37);
nums.Insert(3);
nums.Insert(99);
nums.Insert(22);
nums.InOrder(nums.root);
nums.Delete(23);
Console.WriteLine();
nums.InOrder(nums.root);
nums.Delete(99);
Console.WriteLine();
nums.InOrder(nums.root);
nums.Delete(16);
Console.WriteLine();
nums.InOrder(nums.root);
nums.Delete(3);
Console.WriteLine();
nums.InOrder(nums.root);
}
public Node root;
public BinarySearchTree()
{
root = null;
}
public void Insert(int _data)//插入可排序数据
{
Node newNode = new Node();
newNode.Data = _data;
if (root == null)
root = newNode;
else
{
Node current = root;
Node parent;
while(true)
{
parent = current;
if(_data
十四:希尔排序SheelStort
public void SheelSort()//希尔排序
{
int inner, temp;
int h = 1;
while(h<=count/3)//跨越次数要小于总数的三分之一
{
h = h * 3 + 1;//计算最大跨越次数
}
for(;h>0;h--)//循环跨越次数次
{
for(int outer=h;outerh)&&arr[inner-h]>=temp)//+1是因为inner是下标索引,上一个跨越元素大于当前循环的元素
{
arr[inner] = arr[inner - h];//将较大的跨越元素赋值给较小的没跨越元素(里循环是从大的下标循环到小下标)
inner -= h;//继续往左缩小h个坐标
}
arr[inner] = temp;//
}
}
}
十五:最小生成树、深度优先搜索、广度优先搜索、括扑排序
class Vertex
{
public bool wasVisited;//有无访问过
///
/// 标签
///
public string label;
public Vertex(string lab)
{
label = lab;
wasVisited = false;
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Graph
{
//括扑排序的主要设计点:
//1.用行(row)索引来表示Vertex顶点索引,顶点存储额外信息
//2.用行(row)和列来表示连接路径(Edge边),连接路径的行(row)必须大于列。如(0,1)
//所以添加到栈的时候可以从最后列开始,往上添加
class Graph
{
private int UNM_VERTICES = 6;//图最多存顶点数
private Vertex[] vertices;
private int[,] adjMatrix;//边的临边矩阵
int numVers;//当前顶点数
//===深度优先搜索===========
public void DepthFirstSearch()
{
Stack gStack = new Stack();
vertices[0].wasVisited = true;
gStack.Push(0);//将第一个顶点放入栈
ShowVertex(0);//显示第一个顶点,的label
int v;//顶点序号
while(gStack.Count>0)//如果栈里还有顶点就继续循环
{
v = GetAdjUnvisitedVertex(gStack.Peek());//从最后添加进来的开始找
if(v==-1)
{
gStack.Pop();
}
else
{
vertices[v].wasVisited = true;
ShowVertex(v);
gStack.Push(v);
}
}
for (int j = 0; j < UNM_VERTICES; j++)
vertices[0].wasVisited = false;
}
private int GetAdjUnvisitedVertex(int v)//获取某个顶点相邻的未访问过的顶点
{
for(int j=0;j gQueue = new Queue();
vertices[0].wasVisited = true;
ShowVertex(0);
gQueue.Enqueue(0);
int vert1, vert2;
while(gQueue.Count>0)
{
vert1 = gQueue.Dequeue();//返回并删除最先加进来的对象
vert2 = GetAdjUnvisitedVertex(vert1);//找未访问的顶点
while(vert2!=-1)
{
vertices[vert2].wasVisited = true;
ShowVertex(vert2);
gQueue.Enqueue(vert2);//添加到先进先出队列里
vert2 = GetAdjUnvisitedVertex(vert1);
}
}
for (int j = 0; j < UNM_VERTICES; j++)
vertices[0].wasVisited = false;
}
//==========================
//=======最小生成树算法==========
public void Mst()
{
Stack gStack = new Stack();
vertices[0].wasVisited = true;
gStack.Push(0);
int currVertex, ver;
while(gStack.Count>0)
{
currVertex = gStack.Peek();
ver = GetAdjUnvisitedVertex(currVertex);
if(ver==-1)
{
gStack.Pop();
}
else
{
vertices[ver].wasVisited = true;
gStack.Push(ver);
Console.Write(vertices[currVertex].label);
Console.Write(vertices[ver].label);
Console.Write(" ");
}
}
for (int j = 0; j < UNM_VERTICES; j++)
vertices[0].wasVisited = false;
}
//==========================
static void Main()
{
Graph aGraph = new Graph(13);
aGraph.AddVertex("A");
aGraph.AddVertex("B");
aGraph.AddVertex("C");
aGraph.AddVertex("D");
aGraph.AddVertex("E");
aGraph.AddVertex("F");
aGraph.AddVertex("G");
aGraph.AddEdge(0, 1);
aGraph.AddEdge(0,2);
aGraph.AddEdge(0,3);
aGraph.AddEdge(1,2);
aGraph.AddEdge(1,3);
aGraph.AddEdge(1,4);
aGraph.AddEdge(2,3);
aGraph.AddEdge(2,5);
aGraph.AddEdge(3,5);
aGraph.AddEdge(3,4);
aGraph.AddEdge(3,6);
aGraph.AddEdge(4,5);
aGraph.AddEdge(4,6);
aGraph.AddEdge(5,6);
aGraph.Mst();//最小生成树
Console.Read();
//aGraph.AddVertex("A");
//aGraph.AddVertex("B");
//aGraph.AddVertex("C");
//aGraph.AddVertex("D");
//aGraph.AddVertex("E");
//aGraph.AddVertex("F");
//aGraph.AddVertex("G");
//aGraph.AddVertex("H");
//aGraph.AddVertex("I");
//aGraph.AddVertex("J");
//aGraph.AddVertex("K");
//aGraph.AddVertex("L");
//aGraph.AddVertex("M");
//aGraph.AddEdge(0, 1);//AB
//aGraph.AddEdge(1,2);//BC
//aGraph.AddEdge(2, 3);//CD
//aGraph.AddEdge(0, 4);//AE
//aGraph.AddEdge(4, 5);//EF
//aGraph.AddEdge(5, 6);//FG
//aGraph.AddEdge(0, 7);//AH
//aGraph.AddEdge(7, 8);//
//aGraph.AddEdge(8, 9);//
//aGraph.AddEdge(0, 10);//AK
//aGraph.AddEdge(10, 11);//
//aGraph.AddEdge(11, 12);//
// aGraph.DepthFirstSearch();//深度优先搜索
//aGraph.BreadthFirstSearch();//广度优先搜索
//Graph theGraph = new Graph(4);//括扑排序
//theGraph.AddVertex("A");//0
//theGraph.AddVertex("B");//1
//theGraph.AddVertex("C");//2
//theGraph.AddVertex("D");//3
//theGraph.AddEdge(0, 1);
//theGraph.AddEdge(1, 2);
//theGraph.AddEdge(2, 3);
//theGraph.TopSort();
}
public Graph(int numvertices)
{
UNM_VERTICES = numvertices;
vertices = new Vertex[UNM_VERTICES];
adjMatrix = new int[UNM_VERTICES, UNM_VERTICES];
numVers = 0;
for(int outer=0;outer gStack = new Stack();
while(UNM_VERTICES>0)
{
int currVertex = NoSuccessors();
if(currVertex==-1)
{
Console.WriteLine("Error:图没有找到后继顶点");
return;
}
gStack.Push(vertices[currVertex].label);
DelVertex(currVertex);
}
Console.WriteLine("括扑排序的结果:");
while(gStack.Count>0)
{
Console.Write(gStack.Pop() + " ");
}
}
public int NoSuccessors()//查找无后续顶点的顶点
{
bool isEdge;
for(int row=0;row0)//有后继顶点
{
isEdge = true;
break;
}
}
if (isEdge == false)//说明这被当前顶点数限制列的行没有大于0的边,找到后继顶点。添加到栈中
return row;
}
return -1;
}
public void DelVertex(int vert)//要删除的顶点,从0开始
{
if(vert!=UNM_VERTICES-1)//如果删除的不是最后一行
{
for(int j=vert;j
十六:最短路径
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Graph
{
class Graph
{
private int[,] adjMatrix;//边的领接矩阵
private const int max_verts = 20;
int startToCurrent;
int currentVert;
///
/// 最大值,表示未连接
///
int infinity = 100000;
Vertex[] vertexList;
///
/// 图里面加了几个顶点
///
int nVerts;
///
/// 加到树VertexList里几个顶点
///
int nTree;
///
/// 最短路径
///
DistOriginal[] sPath;
//======================
static void Main()
{
Graph aGraph = new Graph();
aGraph.AddVertex("A");
aGraph.AddVertex("B");
aGraph.AddVertex("C");
aGraph.AddVertex("D");
aGraph.AddVertex("E");
aGraph.AddVertex("F");
aGraph.AddVertex("G");
aGraph.AddEdge(0, 1, 2);
aGraph.AddEdge(0, 3, 1);
aGraph.AddEdge(1, 3, 3);
aGraph.AddEdge(1, 4, 10);
aGraph.AddEdge(2, 5, 5);
aGraph.AddEdge(2, 0, 4);
aGraph.AddEdge(3, 2, 2);
aGraph.AddEdge(3, 5, 8);
aGraph.AddEdge(3, 4, 2);
aGraph.AddEdge(3, 6, 4);
aGraph.AddEdge(4, 6, 6);
aGraph.AddEdge(6, 5, 1);
aGraph.Path();
Console.Read();
}
public Graph()
{
vertexList = new Vertex[max_verts];
adjMatrix = new int[max_verts, max_verts];
nVerts = 0;
nTree = 0;
for(int outer=0;outer