zoukankan      html  css  js  c++  java
  • 插入排序,二分查找插入排序,使用二叉树的插入排序


    1. using System;
    2. using System.Collections.Generic;
    3. using System.Linq;
    4. using System.Text;
    5. using System.Threading.Tasks;
    6. /**
    7. * 插入排序
    8. * **/
    9. namespace Algorithm {
    10. class InsertionSort<T> where T:IComparable{
    11. //插入排序
    12. static public void ISort(T[] arr) {
    13. int i, j;
    14. for (i = 1; i < arr.Length; i++) {
    15. if (arr[i].CompareTo(arr[i - 1]) < 0) {
    16. T temp = arr[i];
    17. for (j = i - 1; j>=0 && arr[j].CompareTo(temp) > 0; j--) {
    18. arr[j + 1] = arr[j];
    19. }
    20. arr[j + 1] = temp;
    21. }
    22. }
    23. }
    24. //二分查找
    25. static public int BinarySearch(T[] arr,int start,int end, T x) {
    26. while (start < end) {
    27. int mid = start + (end - start) / 2 ;
    28. T midData = arr[mid];
    29. if (midData.CompareTo(x) > 0) {
    30. end = mid - 1;
    31. } else {
    32. start = mid + 1;
    33. }
    34. }
    35. return start;
    36. }
    37. //二分查找插入排序
    38. static public void ISortBinarySearch(T[] arr) {
    39. int n = arr.Length;
    40. for (int i = 1; i < n; i++) {
    41. if (arr[i].CompareTo(arr[i - 1]) < 0) {
    42. T temp = arr[i];
    43. int insertIndex = BinarySearch(arr, 0, i, temp);
    44. for (int j = i - 1; j >= insertIndex; j--) {
    45. arr[j + 1] = arr[j];
    46. }
    47. arr[insertIndex] = temp;
    48. }
    49. }
    50. }
    51. static public T[] ISortBSTree(T[] arr) {
    52. BSTree<T> tree = new BSTree<T>(arr);
    53. return tree.ToList().ToArray();
    54. }
    55. }
    56. }


    普通插入排序:比较了O(n^2)次,移动了O(n^2)次

    二分搜索插入排序:比较了O(nlogn)次,移动了O(n^2)次,时间复杂度仍是O(n^2)

    使用二叉树的插入排序:时间复杂度为O(nlgn),达到了基于比较的排序算法的时间下限




  • 相关阅读:
    JavaScript中的原型和继承
    Classical Inheritance in JavaScript
    jquery.cookie 使用方法
    Backbone.js 使用 Collection
    Backbone.js 中使用 Model
    Backbone.js 使用模板
    Java并发编程:volatile关键字解析zz
    eclipse 搭建Swt 环境
    Adams输出宏代码
    根据圆上三点求圆心及半径
  • 原文地址:https://www.cnblogs.com/xiejunzhao/p/051b8d9a7aacf13cd98642a31f6738cb.html
Copyright © 2011-2022 走看看