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

    View Code
     1 package com.test.suanfa;
     2 
     3 public class QuickSoft {
     4 
     5     private void swap(int a[], int i, int j) {
     6         int tmp = a[i];
     7         a[i] = a[j];
     8         a[j] = tmp;
     9     }
    10 
    11     private int partition(int a[], int p, int r) {
    12         int point = a[r];
    13         // 将小于等于point的元素移到左边区域
    14         // 将大于point的元素移到右边区域
    15         int index = p;
    16         for (int i = index; i < r; ++i) {
    17             if (a[i] - point <= 0) {
    18                 swap(a, index++, i);
    19                 System.out.println("    交换之后分组为~~~~~~~~~~~"+i+"~~~~~~~~~~~~~~~~~");
    20                 for (int j = 0; j < a.length; j++) {
    21                     System.out.print(a[j]+" ");
    22                 }
    23                 System.out.println();
    24                 //System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~");
    25             }
    26         }
    27         swap(a, index, r);
    28         return index;
    29     }
    30 
    31     public void qsort(int a[], int p, int r) {
    32         if (p < r) {
    33             // 确定拆分点,并对数组元素进行移动
    34             // 这是快速排序算法的关键步骤
    35             int q = partition(a, p, r);
    36             // 对左半段排序
    37             qsort(a, p, q - 1);
    38             // 对右半段排序
    39             qsort(a, q + 1, r);
    40         }
    41     }
    42 
    43     public static void main(String[] args) {
    44         // 声明一个类
    45         QuickSoft ms = new QuickSoft();
    46         int len = 10;
    47         int a[]={5,1,2,9,3,0,8,4,7,6};
    48         // 初始化a数组
    49 
    50         ms.partition(a, 0, len - 1);
    51         for (int i = 0; i < a.length; i++) {
    52             System.out.print(a[i]+" ");
    53         }
    54         System.out.println();
    55         System.out.println("---------------------");
    56         // 快速排序
    57         ms.qsort(a, 0, len - 1);
    58 
    59         System.out.println("排序后的数组如下:");
    60         for (int i = 0; i < a.length; i++) {
    61             System.out.print(a[i]+" ");
    62         }
    63 
    64     }
    65 }
  • 相关阅读:
    tableviewCell折叠状态1
    iOS中--NSArray调用方法详解 (李洪强)
    NSNumber的使用
    Fedora13下编译busybox-1.15.0出现can not find lcrypt错误
    【独立开发人员er Cocos2d-x实战 013】Cocos2dx 网络编程实战之星座运势
    JAVA序列化的作用
    我买网B轮融资成功,五周年豪掷千万回馈会员
    一步步教你搭建TinyOS2.1.2开发环境
    POJ2947 DAZE [Gauss]
    慢慢理解RESTful架构
  • 原文地址:https://www.cnblogs.com/wangchy0927/p/2496026.html
Copyright © 2011-2022 走看看