zoukankan      html  css  js  c++  java
  • Java实现快速排序算法

     1 package xiaoling;
     2 public class QuickSort{
     3         public static void main(String[] args){
     4                 int[] nums = new int[20];
     5                 for (int loc = 0; loc < nums.length; ++loc){
     6                         nums[loc] = (int) (Math.random() * 100) + 5;
     7                 }
     8                 for (int num: nums) System.out.print(num + " ");
     9                 System.out.println("
    -----------------------");
    10                 QS(nums, 0, nums.length-1);
    11                 for (int num: nums) System.out.print(num + " ");
    12                 System.out.println();
    13         }
    14         public static  void QS(int[] nums, int low, int high){
    15                 if (low >= high) return;
    16                 int mid = getMiddle(nums, low, high);
    17                 QS(nums, mid+1, high);
    18                 QS(nums, 0, mid-1);
    19         }
    20         public static int getMiddle(int[] nums, int low, int high){
    21                 int temp = nums[low];
    22                 while (low < high){
    23                         while (low < high && nums[high] >= temp) --high;
    24                         nums[low] = nums[high];
    25                         while (low < high && nums[low] <= temp) ++low;
    26                         nums[high] = nums[low];
    27                 }
    28                 nums[low] = temp;
    29                 return low;
    30         }
    31 }

    运行结果:

  • 相关阅读:
    ibatis报错
    struts配置时遇到的几个问题
    快乐工作,快乐生活
    浅谈协方差矩阵理解篇
    类成员变量初始化
    类对象所占内存空间总结
    const 成员函数
    Qt对话框QDialog
    const引用返回值
    Qt 对象间的父子关系
  • 原文地址:https://www.cnblogs.com/wangling1820/p/11696509.html
Copyright © 2011-2022 走看看