• 交互设计算法基础(3)


     1 int pivotIndex, pivot, swapIndex;
     2 
     3 void swap(int[] arr, int x, int y) {
     4   int temp = arr[x];
     5   arr[x] = arr[y];
     6   arr[y] = temp;
     7 }
     8 
     9 void quickSort(int[] arr, int start, int end) {
    10   if (end <= start) return;
    11 
    12   pivotIndex = (start + end)/2;
    13   pivot = arr[pivotIndex];
    14   swap(arr, pivotIndex, end);
    15   swapIndex = start;
    16   for (int i = start; i < end; i++) {
    17     if (arr[i] <= pivot) {
    18       swap(arr, i, swapIndex);
    19       ++swapIndex;
    20     }
    21   }
    22   swap(arr, swapIndex, end);
    23 
    24   quickSort(arr, start, swapIndex-1);
    25   quickSort(arr, swapIndex+1, end);
    26 } 
    27 
    28 void draw() {
    29   noLoop();
    30   int[] arr = {10, 5, 2, 3};
    31   quickSort(arr, 0, arr.length-1);
    32   println(arr);
    33 }

    快速排序,说白了就是快啦,不过有两种实现方式,一种普通,一种In-place,后面的比前面的占用较少空间。

    快排用分治法解决。

    最佳时间复杂度:O(nlog n)

    平均时间复杂度:O(nlog n)

    最差时间复杂度:O(n2)

    空间复杂度:一般版本O(n),In-place O(log n)

    爱好编程、喜欢计算机、也喜欢美食~
  • 相关阅读:
    nginx
    不再想写博客的大众集合教程
    数据结构与算法之算法
    数据结构与算法
    yii2的安装使用
    git的使用方法总结
    php生成图片验证码
    git推送失败的问题
    配置nginx支持thinkphp框架
    centos下的lnmp环境搭建
  • 原文地址:https://www.cnblogs.com/x5115x/p/7530765.html
Copyright © 2020-2023  润新知