快速排序算法讲解c++

//

//  main.cpp

//  quick-sort

//

//  Created by mac on 2020/6/4.

//  Copyright © 2020 mac. All rights reserved.

//

//快速排序的总体的算法就是利用二分法,最终把数组进行排序
在一组数组里面进行选择一个数字然后通过这个数字对数据进行分割,比这个数大的放到左边,比这个数小的放到右边
//然后通过递归的方式进行不断递归知道数组数据排序完成

#include <iostream>

 int partition(int unsorted[], int low, int high)

{

    int pivot = unsorted[low];

    while (low < high)//有时候第一次不能一次对所有的数据分割好

    {

        while (low < high && unsorted[high] > pivot) high--;//如果遇到大的就进行往前移动

        unsorted[low] = unsorted[high]; //移到前面

        while (low < high && unsorted[low] <= pivot) low++;//如果遇到的比priov小就向前,移动一个

        unsorted[high] = unsorted[low];

        for(int i=0;i<6;i++){

            std::cout<<unsorted[i]<< ",";

        }

        std::cout<< ""<<std::endl;

    }

    unsorted[low] = pivot;

    return low;

}



 void quick_sort(int unsorted[], int low, int high)

{

    int loc = 0;

    if (low < high)

    {

        loc = partition(unsorted, low, high);

        quick_sort(unsorted, low, loc - 1);

        quick_sort(unsorted, loc + 1, high);

    }

}



int main(int argc, const char * argv[]) {

    // insert code here...

    int x[] = { 6, 5, 4, 9, 8, 7 };

    for(int i=0;i<6;i++){

        std::cout<<x[i]<< ",";

    }

    std::cout <<"" <<std::endl;

    int len = sizeof(x)/sizeof(x[0]);

    quick_sort(x, 0, len - 1);



    return 0;

}

 

 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值