【TypeScript】類
阿新 • • 發佈:2021-01-09
技術標籤:c#
///
/// 桶排序
/// 類似於雜湊表的拉鍊法,定義一個對映函式,將值放入對應的桶中
/// 最壞時間情況:全部分到一個桶中O(N^2),一般情況為O(NlogN)
/// 最好時間情況:每個桶中只有一個數據時最優O(N)
/// int bucketNum = arr.Length;
/// 對映函式:int bucketIndex = arr[i] * bucketNum / (max + 1);
///
///
/// 陣列的最大值
///
private static int[] BucketSort(int[] arr, int max, int min)
{
int bucketNum = arr.Length;
// 初始化桶 LinkedList<int>[] bucket = new LinkedList<int>[arr.Length]; for (int i = 0; i < bucketNum; i++) { bucket[i] = new LinkedList<int>(); } // 元素分裝各個桶中 for (int i = 0; i < bucketNum; i++) { //對映函式 int bucketIndex = arr[i] * bucketNum / (max + 1); InsertIntoLinkList(bucket[bucketIndex], arr[i]); } // 從各個桶中獲取後排序插入 int index = 0; for (int i = 0; i < bucketNum; i++) { foreach (var item in bucket[i]) { arr[index++] = item; } } return arr; } /// <summary> /// 按升序插入 linklist /// </summary> /// <param name="linkedList"> 要排序的連結串列 </param> /// <param name="num"> 要插入排序的數字 </param> private static void InsertIntoLinkList(LinkedList<int> linkedList, int num) { // 連結串列為空時,插入到第一位 if (linkedList.Count == 0) { linkedList.AddFirst(num); return; } else { foreach (int i in linkedList) { if (i > num) { System.Collections.Generic.LinkedListNode<int> node = linkedList.Find(i); linkedList.AddBefore(node, num); return; } } linkedList.AddLast(num); } }