zoukankan      html  css  js  c++  java
  • 三数中值快速排序(长度小于3的数组转插入排序)

    void insertSort(int a[], int len)
    {
        for (int i = 1; i < len; ++i)
        {
            int j;
            int temp = a[i];
            for (j = i - 1; j >= 0; --j)
            {
                if (a[j] <= temp)
                    break;
                a[j + 1] = a[j];
            }
            a[j + 1] = temp;
        }
    }
    
    void swap(int *a, int *b)
    {
        int temp = *a;
        *a = *b;
        *b = temp;
    }
    
    int median3(int a[], int left, int right)
    {
        int center = (left + right) >> 1;
        if (a[left] > a[center])
            swap(&a[left], &a[center]);
        if (a[left] > a[right])
            swap(&a[left], &a[right]);
        if (a[center] > a[right])
            swap(&a[center], &a[right]);
        swap(&a[center], &a[right - 1]); // hide pivot
        return a[right - 1];
    }
    
    const int cutoff = 3;
    
    void quickSort(int a[], int left, int right)
    {
        int i, j;
        int pivot;
        if (left + cutoff <= right)
        {
            pivot = median3(a, left, right);
            i = left, j = right - 1;
            while (true)
            {
                while (a[++i] < pivot) {}
                while (a[--j] > pivot) {}
                if (i < j)
                    swap(&a[i], &a[j]);
                else
                    break;
            }
            swap(&a[i], &a[right - 1]); // restore pivot
            quickSort(a, left, i - 1);
            quickSort(a, i + 1, right);
        }
        else
            insertSort(a + left, right - left + 1);
    }
  • 相关阅读:
    python
    C++的socket编程学习
    GooglePlay
    GooglePlay
    Admob
    cocos2dx
    cocos2dx
    cocos2dx
    cocos2dx
    浅谈白鹭Egret
  • 原文地址:https://www.cnblogs.com/sdlwlxf/p/5120496.html
Copyright © 2011-2022 走看看