桶排序(C#)

桶排序(C#)

代码实现:

/// <summary> /// 桶排序 /// </summary> /// <param name=”arrayToSort”>待排序的数组(该数组的元素在[0-1) )</param> /// <returns>排序后的结果</returns> public static double[] BucketSort(double[] arrayToSort) { // 桶 LinkedList<double>[] bucket = new LinkedList<double>[10]; // 初始化桶 for (int i = 0; i < 10; i++) { bucket[i] = new LinkedList<double>(); } // 元素分装到各桶 for (int i = 0; i < arrayToSort.Length; i++) { int bucketIndex = (int)(arrayToSort[i] * 10d); // 添加并进行插入排序 InsertToLinkList(bucket[bucketIndex], arrayToSort[i]); } // 各桶排序 int index = 0; for (int i = 0; i < 10; i++) { foreach (var item in bucket[i]) { arrayToSort[index++] = item; } } return arrayToSort; } /// <summary> /// 按升序插入 /// </summary> /// <param name=”linkedList”>要排序的链表</param> /// <param name=”num”>要插入排序的数字</param> private static void InsertToLinkList(LinkedList<double> linkedList, double num) { if (linkedList.Count == 0) { linkedList.AddFirst(num); return; } for (int i = linkedList.Count – 1; i >= 0; i–) { if (linkedList.ElementAt(i) <= num) { LinkedListNode<double> node = linkedList.FindLast(linkedList.ElementAt(i)); linkedList.AddAfter(node, num); } } }

点赞