quick sort

快速排序(Quicksort),又称划分交换排序(partition-exchange sort),一种排序算法,最早由东尼·霍尔提出。在平均状况下,排序n个项目要Ο(n log n)次比较。在最坏状况下则需要Ο(n2)次比较,但这种状况并不常见。事实上,快速排序通常明显比其他Ο(n log n)算法更快,因为它的内部循环(inner loop)可以在大部分的架构上很有效率地被实现出来。 
快速排序也是被称作21世纪最伟大算法之一。

void quick_sort(int *a, int left, int right)
{
    if(left >= right)/*如果左边索引大于或者等于右边的索引就代表已经整理完成一个组了*/
    {
        return ;
    }
    int i = left;
    int j = right;
    int key = a[left];

    while(i < j)                               /*控制在当组内寻找一遍*/
    {
        while(i < j && key <= a[j])
            /*而寻找结束的条件就是,1,找到一个小于或者大于key的数(大于或小于取决于你想升
        序还是降序)2,没有符合条件1的,并且i与j的大小没有反转*/
        {
            j--;/*向前寻找*/
        }

        a[i] = a[j];
        /*找到一个这样的数后就把它赋给前面的被拿走的i的值(如果第一次循环且key是
        a[left],那么就是给key)*/

        while(i < j && key >= a[i])
            /*这是i在当组内向前寻找,同上,不过注意与key的大小关系停止循环和上面相反,
        因为排序思想是把数往两边扔,所以左右两边的数大小与key的关系相反*/
        {
            i++;
        }

        a[j] = a[i];
    }

    a[i] = key;/*当在当组内找完一遍以后就把中间数key回归*/
    quick_sort(a, left, i - 1);/*最后用同样的方式对分出来的左边的小组进行同上的做法*/
    quick_sort(a, i + 1, right);/*用同样的方式对分出来的右边的小组进行同上的做法*/
    /*当然最后可能会出现很多分左右,直到每一组的i = j 为止*/
}
/*!
 * Description:
 * author scictor <[email protected]>
 * date 2018/7/22
 */


int partition ( int array[], int min, int max)
{
    // define a pivot as the max item of the (sub)array
    int pivot = array[max] ;
    int i = min - 1 ;
    // loop through the elements of the (sub)array
    for ( int j = min ; j < max ; j ++ )
    {
        // in case the element has a smaller value that the pivot
        // bring it in front of it (larger elements will come after it)
        if (array[j] <= pivot)
        {
            i ++ ;
            int temp = array[i] ;
            array[i] = array[j] ;
            array[j] = temp ;
        }
    }
    // bring the pivot to its correct position
    int temp = array[i + 1] ;
    array[i + 1] = array[max] ;
    array[max] = temp ;
    return i + 1 ;
}
void quickSort ( int array[], int min, int max)
{
    if (min < max)
    {
        // partition the array in two parts
        int q = partition(array, min, max) ;
        // apply QuickSort recursively to both parts
        quickSort(array, min, q - 1) ;
        quickSort(array, q + 1, max) ;
    }
}

猜你喜欢

转载自www.cnblogs.com/guxuanqing/p/9351565.html