C#冒泡排序

冒泡排序,helper帮助类,里面写一了一个给int数组排序的的非静态方法,然后将排序好的数组返回。

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

namespace SortHelper
{
    public class BubbleSortHelper
    {
        public int[] BubbleSortIntArray(int[] intArray)
        {
            int[] array = new int[intArray.Count()];
            if (intArray.Count() == 0)
            {
                return array;
            }
            int length = intArray.Length;
            int temp = 0;
            for (int i = 0; i < length - 1; i++)//冒泡排序,两两比较,小的在前,大的在后
            {
                for (int j = 0; j < length - 1 - i; j++)
                {
                    if (intArray[j] > intArray[j + 1])
                    {
                        temp = intArray[j];
                        intArray[j] = intArray[j + 1];
                        intArray[j + 1] = temp;
                    }
                }
            }

            array = intArray;
            return array;
        }
    }
}

在main方法中调用该排序方法……

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

namespace SortHelper
{
    class Program
    {
        static void Main(string[] args)
        {
            //调用冒泡排序的int 数组
            int[] testArray = {1,3,9,4,5,3,2,5,4,5,8,8,8 };
            BubbleSortHelper bsh = new BubbleSortHelper();
            int[] result = bsh.BubbleSortIntArray(testArray);
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < result.Count(); i++)
            {
                sb.Append(result[i] + ",");
            }
            sb.Remove(sb.Length - 1,1);
            Console.WriteLine(sb);
            Console.ReadLine();
        }
    }
}

执行结果:

冒泡排序

你可能感兴趣的:(C#冒泡排序)