秒懂快速排序

//
//  main.cpp
//  quicksort_project
//
//  Created by fantasy on 18/3/26.
//  Copyright © 2018年 fantasy. All rights reserved.
//


#include <iostream>




void quickSort(int arr[],int start,int end)
{
    if( start < end)//its the end
    {
        int i = start,j = end,temp = arr[start];//设定一个分界,就随便以第一个数为分界
        while(i < j)
        {
            while(i < j && temp <= arr[j])//从后往前找,找到第一个比temp小的
                j --;//find the first smaller than temp
            if(i < j)//can not wait i,j comes together
            {
                arr[i ++] = arr[j];//exchange arr[j] to the front
                //先把 找到的这个数把这个数放到最前面
            }
        
            while(i < j && arr[i] < temp)//found the first bigger than temp;找到第一个比temp大的
                 i ++;
        
            if(i < j)//forbid i,j comes together if so ,its must goto the end
            {
                arr[j --] = arr[i];//put
                //把找到的这个第一个大于分界的数 放到前面挪动的arr[j]这个位置
            }
        }
        arr[i] = temp;//这样一轮下来,最终要把temp找到数组调整的第一轮中间放着
        quickSort(arr,start,i - 1);//递归排序前面一段
        quickSort(arr,i + 1,end);//递归排序后面一段
    }
}




int main(int argc, const char * argv[]) {
    // insert code here...
    std::cout << "Hello, World!\n";
    int arr[]={9,2,3,1,4,6,10,8,5,7};
    quickSort(arr, 0, 9);
    for(int i = 0;i<10;i++)
    {
        printf("%d ",arr[i]);
    }
    printf("\n\n");
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值