JAVA 编写交换类排序 ----快速插入排序算法

package 交换类排序;

import java.util.ArrayList;

/**
 * @auther 刘璐瑶
 * @Year 2020/8/26
 * @time 19:42
 * 笔记:
 */
public class TestQuickSort {
    public static void main(String[] args) {

        int []num =new int[]{3,2,5,1,7};
        QuickSort quickSort = new QuickSort();
        System.out.println("数组为:");
        quickSort.print(num);

        // 调用 快速排序算法
        quickSort.quick(num);

        System.out.println();
        System.out.println("快排结果为: ");
        quickSort.print(num);
    }

}


  class  QuickSort{

      public  void quick(int[] num) {
          if(num.length>0){
              quickSort(num,0,num.length-1);
          }
      }

      // 快速排序 递归调用算法。
      private   void quickSort(int[] a, int low, int high) {
         if (low < high) {
              int middle = getMiddle(a, low, high);
              quickSort(a, 0, middle - 1);
              quickSort(a, middle + 1, high);

          }
      }


      // 快速排序算法需要递归求子序列的排序。
      private  int getMiddle(int[] a, int low, int high) {
          // 设置哨兵
          int temp = a[low];
          // 如果 哨兵 小于 a[high] 表示不需要交换
          while( low < high){
              while( low< high && temp<= a[high]){
                  high -- ;
              }
              // 找到 需要交换的元属后
              a[low] = a[high];

              // 当 哨兵大于该值时 交换
              while(low < high&&a[low]<=temp){
                  low++ ;
              }
              a[high]=  a[low];
          }
          // 返回当前确认结点的下标,方便进行 递归。
          a[low] = temp;
          return  low;
      }

      // 打印函数
      public  void print(int a[]) {
          for (int i = 0; i < a.length; i++) {
              System.out.print(a[i]+"  ");
          }
      }


  }

 

posted @ 2020-08-26 21:01  LY心情笔记  阅读(52)  评论(0)    收藏  举报