zoukankan      html  css  js  c++  java
  • 什么是快速排序?

    package com.example.demo;

    import java.util.Arrays;
    import java.util.HashMap;
    import java.util.Map;
    import java.util.Stack;

    public class QuickSortWithStack {
    public static void quickSort(int[] arr,int startIndex,int endIndex) {
    //递归的退出条件:递归最后一层左边的元素小于或等于右边元素的位置
    if(startIndex >= endIndex) {
    return;
    }
    //得到基准元素的位置

    //取第一个位置的元素作为基准元素
    int pivot = arr[startIndex];
    int left = startIndex;
    int right = endIndex;

    /*
    * 第一步:选定基准元素pivot,设置左指针left和右指针right
    * 第二步:第1次循环,从right指针开始,让指针指向的元素与基准元素作比较。
    * 第三步:如果大于或等于pivot则指针左移,否则停止移动转到left指针
    * 第四步:如果left指针指向的元素小于或等于pivot,则指针向左移动
    * 第五步:如果大于,则转到right指针
    * 第六步:直到left指针和right指针相遇
    */
    while(left != right) {
    while(left<right && arr[right] > pivot) {
    right--;
    }
    while(left<right && arr[left] <= pivot ) {
    left++;
    }
    if(left<right) {
    int p = arr[left];
    arr[left] = arr[right];
    arr[right] = p;
    }
    }
    //pivot和指针重合点交换
    arr[startIndex] = arr[left];
    arr[left] = pivot;

    int pivotIndex = left;
    //根据基准元素,递归调用
    quickSort(arr,startIndex,pivotIndex-1);
    quickSort(arr,pivotIndex+1,endIndex);
    }

    public static void main(String[] args) {

    int[] arr={9,4,32,2,6};
    // int[] arr= {4,7,6,5,3,2,80,1};

    quickSort(arr, 0, arr.length-1);
    System.out.println(Arrays.toString(arr));
    }
    }
  • 相关阅读:
    Unreal Engine 4 Based Materials
    PhysX Clothing for UE4
    UE4中使用URL图片
    开始创作自己的VR作品——VR故事叙述终极指南
    UE4里的自定义深度功能
    Mybatis27题
    java 备用待迁移
    几个算法题目
    数据结构算法题目
    Mybatis 面试题
  • 原文地址:https://www.cnblogs.com/dongma/p/10092853.html
Copyright © 2011-2022 走看看