算法-快速排序

来源:互联网 发布:j2ee服务器端高级编程 编辑:程序博客网 时间:2024/06/06 13:58

算法思路

  1. 每次遍历将比第一个数小的移动到这个数的左边,将比这个数大的数移到右边,得到这个数的最终位置
  2. 对得到的两个未排序的子数组继续排序

伪代码

  1. 以arr[0]为基准,i=0,j=arr.length - 1
  2. 逆序比较,第一个比基准小的数移动到i的位置
  3. 正序比较,第一个比基准大的数移动到j的位置
  4. 重复上述步骤,直到i=j,令arr[i]为基准的值
  5. 重复以上步骤,直到确认所有数的位置

具体代码

// quicksort// sort arr[] from low to high by quicksort// int [] arr// int low: the start index// int high: the end indexvoid QuickSort(int* arr, int low, int high) {    if (NULL == arr) return;    if (high <= low) return;    int ori_low = low; // the origin low index    int ori_high = high; // the origin high index    int base = arr[low]; // the basekey    while (low < high) {        while (low < high && arr[high] >= base) high--;        if (arr[high] < base) arr[low] = arr[high];        while (low < high && arr[low] <= base) low++;        if (arr[low] > base) arr[high] = arr[low];    }    arr[low] = base;    if (low > ori_low) {        QuickSort(arr, ori_low, low - 1);    }    if (low < ori_high) {        QuickSort(arr, low + 1, ori_high);    }}

算法分析

  1. 时间复杂度:O(nlog2(n))
  2. 非稳定排序
原创粉丝点击