集合(System.Collections)
分为线性集合和非线性集合
线性集合
线性集合:直接存储集合,顺序存储集合(链表,双向链表)
直接存储集合:数组,字符串,Struct结构体
顺序存储集合(链表,双向链表):栈,队列,Dictionary
非线性集合
非线性集合:树,堆,图,集
层次集合:树(红黑树,二叉树,堆(最小的值放到根节点上,会重组元素))
组集合:无序的数据组成的非线性集合被称为组,Set集合,图(旅行商),网络
CollectionBase,ICollection,IEnumerable
顺序查找
顺序查找,无序的数组
/// <summary> /// 顺序查找 /// </summary> /// <param name="arr"></param> /// <param name="sValue"></param> /// <returns></returns> public static int SeqSearch(int[] arr, int sValue) { for (int i = 0; i < arr.Length; i++) { if (arr[i] == sValue) return i; } return -1; }
最大值
/// <summary> /// 最大值 /// </summary> /// <param name="arr"></param> /// <returns></returns> public static int Max(int[] arr) { int max = arr[0]; for (int i = 1; i < arr.Length; i++) { if (arr[i] > max) { max = arr[i]; } } return max; }
最小值
/// <summary> /// 最小值 /// </summary> /// <param name="arr"></param> /// <returns></returns> public static int Min(int[] arr) { int min = arr[0]; for (int i = 1; i < arr.Length; i++) { if (arr[i] < min) { min = arr[i]; } } return min; }
自组织查找
/// <summary> /// 自组织查找 /// </summary> /// <param name="arr"></param> /// <param name="value"></param> /// <returns></returns> public static int CustomSeqSearch(int[] arr, int sValue) { for (int i = 0; i < arr.Length; i++) { if (arr[i] == sValue && i > arr.Length * 0.2) { Swap(arr, i, i - 1); return i - 1; } else { if (arr[i] == sValue) { return i; } } } return -1; }
二叉树查找
/// <summary> /// 二叉查找 /// </summary> /// <param name="arr"></param> /// <param name="sValue"></param> /// <returns></returns> public static int BinarySearch(int[] arr, int sValue) { int upperBound = arr.Length - 1, lowerBound = 0, mid = 0; while (lowerBound <= upperBound) { mid = (lowerBound + upperBound) / 2; if (arr[mid] == sValue) { return mid; } else { if (arr[mid] > sValue) { upperBound = mid - 1; } else { lowerBound = mid + 1; } } } return -1; }
![](https://img2020.cnblogs.com/blog/540519/202105/540519-20210518215557165-1245791518.png)
递归二叉查找
/// <summary> /// 递归二叉查找 /// </summary> /// <param name="arr"></param> /// <param name="value"></param> /// <param name="lower"></param> /// <param name="upper"></param> /// <returns></returns> public static int RBinarySearch(int[] arr, int value, int lower, int upper) { if (lower > upper) { return -1; } else { int mid = (lower + upper) / 2; if (value < arr[mid]) { return RBinarySearch(arr, value, lower, mid - 1); } else if (value == arr[mid]) { return mid; } else return RBinarySearch(arr, value, mid + 1, upper); } }
总结:二叉树查找算法数据越大效果越好,顺序查找算法相反