前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >算法一 快速排序

算法一 快速排序

作者头像
smartsi
发布2019-08-07 15:11:40
2630
发布2019-08-07 15:11:40
举报
文章被收录于专栏:SmartSiSmartSi

1. 分析

2. 伪代码

3. 思路图

4. 运行过程

5. 代码

5.1 C++版本
代码语言:javascript
复制
/*********************************
*   日期:2014-04-01
*   作者:SJF0115
*   题目:快速排序
**********************************/
#include <iostream>
#include <stdio.h>
using namespace std;
//对子数组array[p...r]就地重排
int Partition(int array[],int p,int r){
    int j,temp;
    //定义哨兵
    int x = array[r];
    //i为小于哨兵元素的最后一个元素下标
    int i = p - 1;
    //j为待排序元素的第一个元素
    for(j = p;j < r;j++){
        //跟哨兵比较
        if(array[j] < x){
            i++;
            //交换array[i] array[j]
            temp = array[j];
            array[j] = array[i];
            array[i] = temp;
        }
    }
    //交换array[i+1](大于哨兵元素的第一个元素) array[r]
    temp = array[i+1];
    array[i+1] = array[r];
    array[r] = temp;
    //返回分割下标
    return i + 1;
}
//快排
void QuickSort(int array[],int p,int r){
    if(p >= r || array == NULL){
        return;
    }
    int index = Partition(array,p,r);
    QuickSort(array,p,index-1);
    QuickSort(array,index+1,r);
}

int main()
{
    int array[] = {2,8,7,1,3,5,6,4};
    QuickSort(array,0,7);
    for(int i = 0;i <= 7;i++){
        printf("%d\n",array[i]);
    }
}
5.2 Java版本
代码语言:javascript
复制
package com.sjf.open;

/** 快速排序
 * @author sjf0115
 * @Date Created in 下午5:24 18-3-27
 */
public class QuickSort {

    /**
     * 分割点
     * @param array
     * @param start
     * @param end
     * @return
     */
    int partition(int array[], int start, int end){

        int x = array[end];
        int i = start - 1;
        int tmp;
        for(int j = start;j < end;j++){
            if(array[j] < x){
                i++;
                tmp = array[j];
                array[j] = array[i];
                array[i] = tmp;
            }
        }

        tmp = array[i+1];
        array[i+1] = array[end];
        array[end] = tmp;

        return i+1;

    }

    /**
     * 快速排序
     * @param array
     * @param start
     * @param end
     */
    void quickSort(int array[], int start, int end){

        if(start > end || array == null){
            return;
        }
        int index = partition(array, start, end);
        quickSort(array, start, index-1);
        quickSort(array, index+1, end);

    }

    public static void main(String[] args) {

        QuickSort quickSort = new QuickSort();
        int array[] = {4,1,6,3,9,0};
        quickSort.quickSort(array, 0, 5);
        for(int num : array){
            System.out.println(num);
        }

    }
}
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2017-12-03,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 1. 分析
  • 2. 伪代码
  • 3. 思路图
  • 4. 运行过程
  • 5. 代码
    • 5.1 C++版本
      • 5.2 Java版本
      领券
      问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档