C#之快速排序

//文件中的数据格式为
// 1 2 3 4 5
// 1 2 3 5 6
using System;
using System.Text;
using System.Collections;
using System.IO;
namespace InsertSort
{
    class QS
    {
        public int[] data;  //待排序的数组
        public QS(int n)
        {
            data = new int[n];
        }
        public void QuickSort(int fore, int last)  //快速排序算法
        {
            int begin = fore;
            int end = last;
            int tem = data[fore];  //基准元素
            while (begin < end)   //当左右两端扫描未碰头时
            {
                if (data[end] < tem)  //当基准元素后面的元素大于基准元素后
                {
                    data[begin] = data[end];
                    while (begin < end)
                    {
                        if (data[begin] > tem)
                        {
                            data[end] = data[begin];
                            break;
                        }
                        else
                        {
                            begin++;  //向右挪动
                        }
                    }
                }
                end--;  //向左挪动
            }
            data[begin] = tem;
            if (fore <begin)
            {
                int i = fore;
                int j= begin - 1;
                QuickSort(i,j);
            }
            if (begin < last)
            {
                int i= begin + 1;
                int j = last;
                QuickSort(i, j);
            }
        }
    }
    class Program
    {
        static void Main()
        {
            string path=@"F://test.txt";
            StreamReader sr = new StreamReader(path, Encoding.Default);
            string temp;
            ArrayList aL = new ArrayList();
            while ((temp = sr.ReadLine()) != null)
            {
                string[] s = temp.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);//根据空格区分数据
                int tempInt;
                foreach (string i in s)
                {
                    tempInt = Convert.ToInt32(i);  //string转换成int,基本数据类型的转换
                    aL.Add(tempInt);     //将读取到的数据存入aL中
                }
            }
            int[] data = new int[aL.Count];  //将aL中的数据存入data方便使用排序算法排序
            for (int i = 0; i < aL.Count; i++)
            {
                data[i] = (int)aL[i];
            }
            Console.WriteLine("数组长度{0}", data.Length);
            QS qs = new QS(data.Length);
            for (int i=0;i<data.Length;i++)
            {
                qs.data[i] = data[i];
            }
            int last = data.Length - 1;
            qs.QuickSort(0, last);
            for (int i=0;i<qs.data.Length; i++)
            {
                Console.WriteLine("{0},{1}",qs.data[i],data[i]);
            }
        }
    }
}

原文地址:https://www.cnblogs.com/zztong/p/6695181.html