数据结构常用算法

来源:互联网 发布:暴雪公司 知乎 编辑:程序博客网 时间:2024/05/18 00:44

将一整数序列中的所有负数转移到所有正数之前

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace CSharpTest
{
    class Program
    {
        public static int[] Sort(int[] A)
        {
            int low = 0, high = A.Length - 1;
            int t = A[0];
            while (low < high)
            {
                while (low < high && A[high] >= 0)
                    high--;

                if (low < high)
                {
                    A[low] = A[high];
                    low++;
                }
                low++;
                while (low < high && A[low] < 0)
                    low++;
                if (low < high)
                {
                    A[high] = A[low];
                    high--;
                }
                A[low] = t;
            }
            return A;
        }

        static void Main(string[] args)
        {
            int[] test = new int[] { 10, -19, 88, -81, 100, -25, 778, 22, -971 };
            int[] testResult =  Sort(test);
           
            //print all data
            foreach(int d in testResult)
            {
                Console.Write(d.ToString());
                Console.Write("/n");
            }

            Console.Read();
        }
    }
}

起泡算法

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace CSharpTest
{
    class Program
    {
        static void Main(string[] args)
        {
           int[] test = new int[] { 10, -19, 88, -81, 100, -25, 778, 22, -971 };
           int[] testResult = Bubble(test);
           
            //print all data
            foreach(int d in testResult)
            {
                Console.Write(d.ToString());
                Console.Write("/n");
            }

            Console.Read();
        }

        static int[] Bubble(int[] L)
        {
            int temp;
            for (int i = 0; i < L.Length-1; i++)
            {
                for (int j = 0; j < L.Length-1-i; j++)
                {
                    if (L[j] > L[j + 1])
                    {
                        temp = L[j + 1];
                        L[j + 1] = L[j];
                        L[j] = temp;
                    }
                }
            }
            return L;
        }
    }
}