快速排序

快速排序是一种比选择排序快得多的算法,当然是数据量大的时候,主要思想就是利用一个参考值,将大的组分成两个小的组,一个组都比参考值小,一个组都比参考值大。一直分,分到不能再分,再把每个组和参考值都合并起来


static void Main(string[] args)
{
    List<int> list = new List<int>();
    Random r = new Random();
    for (int i = 0; i < 100000; i++) {
        list.Add(r.Next(1, 10000));
    }
    Stopwatch stopwatch = new Stopwatch();
    stopwatch.Start();
    List<int> sort = quickSort(list);
    stopwatch.Stop();
    foreach (int data in sort) {
        Console.WriteLine(data);
    }

    Console.WriteLine("运行时间:" + stopwatch.ElapsedMilliseconds);

    Console.ReadKey();
}

static List<int> quickSort(List<int> datas) {
    int length = datas.Count;
    //只有一个元素或则没有元素就返回自身(已经排序好了)
    if (length < 2) {
        return datas;
    }

    //随机一个参考数
    Random r = new Random();
    int random_index = r.Next(0, length);
    int val = datas[random_index];
    datas.RemoveAt(random_index);
    List<int> left = new List<int>();//比参考值小的组
    List<int> right = new List<int>();//比参考值大的组

    foreach (int data in datas) {
        if (data < val)
        {
            left.Add(data);
        }
        else {
            right.Add(data);
        }
    }

    left = quickSort(left);
    right = quickSort(right);
    
    //合并起来
    left.Add(val);
    left.AddRange(right);
    return left;
}


快速排序的运行时间:O( nlog(n) )

10W个随机数据排序运行时间:207ms(不知道是不是用了List的原因,还是写法问题,总觉得慢了)

详情看:吃菜网-选择排序和快速排序


首页 我的博客
粤ICP备17103704号