快速排序

来源:互联网 发布:sql 触发器 更新时间 编辑:程序博客网 时间:2024/04/27 15:12

快速排序的概念:
在待排序队列中取一数为标准数,依次将比较区间内的所有数按大小放于该标准数的左右2边.
然后对这2组分别重复上述的方法,直到所有书都排到相应的位置为止.

#include <iostream>

//快速排序
void quickSort(int arr[], int left, int right);

//划分
int partition(int arr[], int left, int right);

//交换
void swapNum(int& x, int& y);

int main(void)
{
    
int arr[10]={36,25,56,54,23,12,34,55,79,8};
    quickSort(arr, 
09);

    
for (int i = 0; i< 10 ; i++)
    
{
        std::cout
<<arr[i]<<std::endl;
    }

    
return 0;
}



void quickSort(int arr[], int left, int right)
{
    
if (left<right)
    
{
        
int pos = partition(arr, left, right);  //寻找划分点
        quickSort(arr, left, pos-1);  //分别排序
        quickSort(arr, pos + 1, right);
    }

}


int partition(int arr[], int left, int right)
{
    
//把第一个数字作为划分点
    int pos = left;

    
//暂存第一个数字
    int temp = arr[left]; 

    
for (int i = left+1; i<=right;i++)
    
{
        
//把小于划分点的数字都放到划分点的左边
        if (temp > arr[i] && ++pos != i)
        
{
            swapNum(arr[i], arr[pos]);
        }

    }


    swapNum(arr[pos], arr[left]); 
//最后,把划分点放到中间
    return pos;
}


void swapNum(int& x, int& y)
{
    
int temp = x;
    x 
= y;
    y 
= temp;
}

原创粉丝点击