算法、结构应用

来源:互联网 发布:mac双系统之后蓝屏 编辑:程序博客网 时间:2024/06/05 06:34

最近又开始找工作,面试、笔试是难免的,这几天多练练手,多写写,很多以前的基础知识略有些手生 :)

int[] iarrary = new int[] { 1, 5, 3, 6, 10, 55, 9, 2, 87, 12, 34, 75, 33, 47 };

各类算法复杂度:

排序法

平均时间

最差情形

稳定度

额外空间

备注

冒泡

O(n2)

O(n2)

稳定

O(1)

n小时较好

交换

O(n2)

O(n2)

不稳定

O(1)

n小时较好

选择

O(n2)

O(n2)

不稳定

O(1)

n小时较好

插入

O(n2)

O(n2)

稳定

O(1)

大部分已排序时较好

基数

O(logRB)

O(logRB)

稳定

O(n)

B是真数(0-9)R是基数(个十百)

Shell

O(nlogn)

O(ns) 1<2

不稳定

O(1)

s是所选分组

快速

O(nlogn)

O(n2)

不稳定

O(nlogn)

n大时较好

归并

O(nlogn)

O(nlogn)

稳定

O(1)

n大时较好

O(nlogn)

O(nlogn)

不稳定

O(1)

n大时较好



1、冒泡排序(两两比较)

        public static void sort(int[] list)        {            int[] newList = new int[list.Length];            int copyValue = 0;            for (int i = 0; i < list.Length - 1;i++)            {                for (int j = i + 1; j < list.Length;j++)                {                    if(list[i] < list[j])                    {                        copyValue = list[i];                        list[i] = list[j];                        list[j] = copyValue;                    }                }            }        }

 

2、选择排序(选择最大的索引,交换值)

        public static void sort(int[] list)        {            int maxIndex = 0;            for (int i = 0; i < list.Length - 1; i++)            {                maxIndex = i;                for (int j = i + 1; j < list.Length; j++)                {                    if (list[j] > list[maxIndex])                    {                        maxIndex = j;                    }                }                int maxValue = list[maxIndex];                list[maxIndex] = list[i];                list[i] = maxValue;            }        }

3、插入排序(后向前, Check, 插入)
  public static void sort(int[] list)        {            for (int i = 1; i < list.Length; i++)            {                int originValue = list[i];                int j = i;                while ((j > 0) && (list[j - 1] > originValue))                {                    list[j] = list[j - 1];                    --j;                }                list[j] = originValue;            }        }


4、希尔排序

     public static void sort(int[] list)        {            int inc;            for (inc = 1; inc <= list.Length / 9; inc = 3 * inc + 1) ;            for (; inc > 0; inc /= 3)            {                for (int i = inc + 1; i <= list.Length; i += inc)                {                    int originValue = list[i - 1];                    int j = i;                    while ((j > inc) && (list[j - inc - 1] > originValue))                    {                        list[j - 1] = list[j - inc - 1];                        j -= inc;                    }                    list[j - 1] = originValue;                }            }        }

 5、快速

/// 快速排序法         /// </summary>         /// <param name="list"></param>         /// <param name="low"></param>         /// <param name="high"></param>         public static void Sort(int[] list, int low, int high)         {             int pivot;             int l, r;             int mid;             if (high <= low)                 return;             else if (high == low + 1)             {                 if (list[low] > list[high])                     Swap(ref list[low], ref list[high]);                 return;             }             mid = (low + high) >> 1;             pivot = list[mid];             Swap(ref list[low], ref list[mid]);             l = low + 1;             r = high;             do             {                 while (l <= r && list[l] < pivot)                     l++;                 while (list[r] >= pivot)                     r--;                 if (l < r)                     Swap(ref list[l], ref list[r]);             } while (l < r);             list[low] = list[r];             list[r] = pivot;             if (low + 1 < r)                 Sort(list, low, r - 1);             if (r + 1 < high)                 Sort(list, r + 1, high);         }

6、递归

二、数据结构:
1、为wssmax些的前序、中序、后序遍历的实现

-- 二叉树遍历 --#region -- 二叉树遍历 --    /**//**//**////创建的是二叉查找树,无重复的结点值    ///特点:左支树中任何值都小于父结点值,右结点任何值大于父结点值(已排序好的结构)    public class TreeNode    {        private TreeNode leftNode;        private TreeNode rightNode;        private int data;        public TreeNode(int nodeData)        {            data = nodeData;            leftNode = rightNode = null;//没有子树        }        public TreeNode LeftNode        {            get            {                return leftNode;            }            set            {                leftNode = value;            }        }        public TreeNode RightNode        {            get            {                return rightNode;            }            set            {                rightNode = value;            }        }        public int Data        {            get            {                return data;            }            set            {                data = value;            }        }        public void Insert(int insertValue)//创建结点        {            if (insertValue < data)            {                if (leftNode == null)                    leftNode = new TreeNode(insertValue);                else                    leftNode.Insert(insertValue);            }            else if (insertValue > data)            {                if (rightNode == null)                    rightNode = new TreeNode(insertValue);                else                    rightNode.Insert(insertValue);            }        }    }    public class Tree    {        private TreeNode root;        public Tree()        {            root = null;        }        //创建树        public void InsertNode(int insertValue)        {            lock (this)            {                if (root == null)                    root = new TreeNode(insertValue);                else                    root.Insert(insertValue);            }        }        //前序遍历        public void PreorderTraversal()        {            lock (this)            {                PreorderHelper(root);            }        }        private void PreorderHelper(TreeNode node)//采用了递归        {            if (node == null)                return;            Console.Write(node.Data + " ");            PreorderHelper(node.LeftNode);            PreorderHelper(node.RightNode);        }        //中序遍历        public void InorderTraversal()        {            lock (this)            {                InorderHelper(root);            }        }        public void InorderHelper(TreeNode node)        {            if (node == null)                return;            InorderHelper(node.LeftNode);            Console.Write(node.Data + " ");            InorderHelper(node.RightNode);        }        //后序遍历        public void PostorderTraversal()        {            lock (this)            {                PostorderHelper(root);            }        }        public void PostorderHelper(TreeNode node)        {            if (node == null)                return;            PostorderHelper(node.LeftNode);            PostorderHelper(node.RightNode);            Console.Write(node.Data + " ");        }    }        #endregion

2、穷小子—链表处理
-- 链表处理 --#region -- 链表处理 --namespace List{    /**//**//**//// <summary>    /// Summary description for ListNode.    /// </summary>    // 结点类    public class ListNode    {        public ListNode(int NewValue)        {            Value = NewValue;        }        /**//**//**//// <summary>        /// 前一个        /// </summary>        public ListNode Previous;        /**//**//**//// <summary>        /// 后一个        /// </summary>        public ListNode Next;        /**//**//**//// <summary>        /// 值        /// </summary>        public int Value;    }    /**//**//**//// <summary>    /// 链表类    /// 定义结点之后开始类线性表的操作编程了.在LIST 类中,采用了,Head ,Tail,  Current,三个指针,    /// 使用Append ,MoveFrist,MovePrevious,MoveNext,MoveLast ,Delete,InsertAscending,InsertUnAscending ,Clear     /// 实现移动,添加,删除,升序插入,降序插入,清空链表操作,GetCurrentValue() 方法取得当前的值。    /// </summary>    public class Clist    {        public Clist()        {            //构造函数            //初始化            ListCountValue = 0;            Head = null;            Tail = null;        }        /**//**//**//// <summary>        /// 头指针        /// </summary>        private ListNode Head;        /**//**//**//// <summary>        /// 尾指针        /// </summary>        private ListNode Tail;        /**//**//**//// <summary>        /// 当前指针        /// </summary>        private ListNode Current;        /**//**//**//// <summary>        /// 链表数据的个数        /// </summary>        private int ListCountValue;        /**//**//**//// <summary>        /// 尾部添加数据        /// </summary>        public void Append(int DataValue)        {            ListNode NewNode = new ListNode(DataValue);            if (IsNull())            //如果头指针为空            {                Head = NewNode;                Tail = NewNode;            }            else            {                Tail.Next = NewNode;                NewNode.Previous = Tail;                Tail = NewNode;            }            Current = NewNode;            //链表数据个数加一            ListCountValue += 1;        }        /**//**//**//// <summary>        /// 删除当前的数据        /// </summary>        public void Delete()        {            //若为空链表            if (!IsNull())            {                //若删除头                if (IsBof())                {                    Head = Current.Next;                    Current = Head;                    ListCountValue -= 1;                    return;                }                //若删除尾                if (IsEof())                {                    Tail = Current.Previous;                    Current = Tail;                    ListCountValue -= 1;                    return;                }                //若删除中间数据                Current.Previous.Next = Current.Next;                Current = Current.Previous;                ListCountValue -= 1;                return;            }        }        /**//**//**//// <summary>        /// 向后移动一个数据        /// </summary>        public void MoveNext()        {            if (!IsEof()) Current = Current.Next;        }        /**//**//**//// <summary>        /// 向前移动一个数据        /// </summary>        public void MovePrevious()        {            if (!IsBof()) Current = Current.Previous;        }        /**//**//**//// <summary>        /// 移动到第一个数据        /// </summary>        public void MoveFrist()        {            Current = Head;        }        /**//**//**//// <summary>        /// 移动到最后一个数据        /// </summary>        public void MoveLast()        {            Current = Tail;        }        /**//**//**//// <summary>        /// 判断是否为空链表        /// </summary>        public bool IsNull()        {            if (ListCountValue == 0)                return true;            return false;        }        /**//**//**//// <summary>        /// 判断是否为到达尾部        /// </summary>        public bool IsEof()        {            if (Current == Tail)                return true;            return false;        }        /**//**//**//// <summary>        /// 判断是否为到达头部        /// </summary>        public bool IsBof()        {            if (Current == Head)                return true;            return false;        }        public int GetCurrentValue()        {            return Current.Value;        }        /**//**//**//// <summary>        /// 取得链表的数据个数        /// </summary>        public int ListCount        {            get            {                return ListCountValue;            }        }        /**//**//**//// <summary>        /// 清空链表        /// </summary>        public void Clear()        {            MoveFrist();            while (!IsNull())            {                //若不为空链表,从尾部删除                Delete();            }        }        /**//**//**//// <summary>        /// 在当前位置前插入数据        /// </summary>        public void Insert(int DataValue)        {            ListNode NewNode = new ListNode(DataValue);            if (IsNull())            {                //为空表,则添加                Append(DataValue);                return;            }            if (IsBof())            {                //为头部插入                NewNode.Next = Head;                Head.Previous = NewNode;                Head = NewNode;                Current = Head;                ListCountValue += 1;                return;            }            //中间插入            NewNode.Next = Current;            NewNode.Previous = Current.Previous;            Current.Previous.Next = NewNode;            Current.Previous = NewNode;            Current = NewNode;            ListCountValue += 1;        }        /**//**//**//// <summary>        /// 进行升序插入        /// </summary>        public void InsertAscending(int InsertValue)        {            //参数:InsertValue 插入的数据            //为空链表            if (IsNull())            {                //添加                Append(InsertValue);                return;            }            //移动到头            MoveFrist();            if ((InsertValue < GetCurrentValue()))            {                //满足条件,则插入,退出                Insert(InsertValue);                return;            }            while (true)            {                if (InsertValue < GetCurrentValue())                {                    //满族条件,则插入,退出                    Insert(InsertValue);                    break;                }                if (IsEof())                {                    //尾部添加                    Append(InsertValue);                    break;                }                //移动到下一个指针                MoveNext();            }        }        /**//**//**//// <summary>        /// 进行降序插入        /// </summary>        public void InsertUnAscending(int InsertValue)        {            //参数:InsertValue 插入的数据            //为空链表            if (IsNull())            {                //添加                Append(InsertValue);                return;            }            //移动到头            MoveFrist();            if (InsertValue > GetCurrentValue())            {                //满足条件,则插入,退出                Insert(InsertValue);                return;            }            while (true)            {                if (InsertValue > GetCurrentValue())                {                    //满族条件,则插入,退出                    Insert(InsertValue);                    break;                }                if (IsEof())                {                    //尾部添加                    Append(InsertValue);                    break;                }                //移动到下一个指针                MoveNext();            }        }    }} #endregion

3、栈操作实现
namespace StackNameSpace{    /**//// <summary>    /// Class1 的摘要说明。    /// </summary>    public class Stack    {        -- 栈类 --#region -- 栈类 --        private int count = 0;        private Node first = null;//定义首结点        public bool Empty        {            get            {                return (first == null);            }        }        public int Count        {            get            {                return count;            }        }        public object Pop()//入栈        {            if (first == null)            {                throw new InvalidOperationException("Can not pop from an empty stack;");            }            else            {                object temp = first.Value;                first = first.Next;                count--;                return temp;            }        }        public void push(object o)//出栈        {            first = new Node(o, first);            count++;        }        public Stack()        {            //            // TODO: 在此处添加构造函数逻辑            //        }        #endregion    }    class Node    {        -- 结点类 --#region -- 结点类 --        public Node Next;        public object Value;        public Node(object value) : this(value, null) { }        public Node(object value, Node next)        {            Next = next;            Value = value;        }        #endregion    }}

三、其他算法
1、
-- 堆排序(小根堆) --#region -- 堆排序(小根堆) --        public static void heapSort(int[] input)        {            int root_count = input.Length / 2;            for (int i = root_count - 1; i >= 0; i--)            {                int left = 0;                int right = 0;                if (2 * i + 1 < input.Length) left = input[2 * i + 1];                if ((2 * i + 2) < input.Length) right = input[2 * i + 2];                if (left >= right && left > input[i])                {                    Sort.swap(ref input[i], ref input[2 * i + 1]);                    Sort.nodeSort(input, 2 * i + 1, input.Length - 1);                }                else if (right >= left && right > input[i])                {                    Sort.swap(ref input[i], ref input[2 * i + 2]);                    Sort.nodeSort(input, 2 * i + 2, input.Length - 1);                }            }            for (int j = input.Length - 1; j > 0; j--)            {                Sort.swap(ref input[0], ref input[j]);                Sort.nodeSort(input, 0, j - 1);            }        }         public static void nodeSort(int[] input, int index,int end)        {            //左孩子存在            while ((2 * index + 1) <= end)            {                //右孩子存在                if ((2 * index + 2) <= end)                {                    //左孩子大                    if (input[2 * index + 1] >= input[2 * index + 2] && input[2 * index + 1] > input[index])                    {                        Sort.swap(ref input[index], ref input[index * 2 + 1]);                        index = 2 * index + 1;                    }                    //右孩子大                    else if (input[2 * index + 2] >= input[2 * index + 1] && input[2 * index + 2] > input[index])                    {                        Sort.swap(ref input[index], ref input[index * 2 + 2]);                        index = 2 * index + 2;                    }                    //父节点大                    else                    {                        return;                    }                }                else                //右孩子不存在                {                    //左孩子大                    if (input[2 * index + 1] > input[index])                    {                        Sort.swap(ref input[index], ref input[index * 2 + 1]);                        index = 2 * index + 1;                    }                    else                    {                        //父节点大                        return;                    }                }            }        }        #endregion