Chinaunix首页 | 论坛 | 博客
  • 博客访问: 104511
  • 博文数量: 41
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 352
  • 用 户 组: 普通用户
  • 注册时间: 2013-09-23 12:37
文章分类

全部博文(41)

文章存档

2015年(1)

2014年(28)

2013年(12)

我的朋友

分类: Java

2014-08-31 13:23:22


点击(此处)折叠或打开

  1. package com.wp;

  2. public class QuickSort {

  3.     /**
  4.      * @param args
  5.      */
  6.     public static void main(String[] args) {
  7.         // TODO Auto-generated method stub
  8.         int []array={1, 20,3,9,5,6,7};
  9.         QuickSort_test(array);
  10.         
  11.         for(int e:array){
  12.              System.out.print(" "+e);
  13.         }
  14.     }
  15.     /**
  16.     *第二种快速排序方法,挖坑填数+分治
  17.     *保存第一个元素到x里面,第一个成为一个坑,数组从后往前找一个比x小的元素(在位置j处)填到前面的坑里,这样后面(位置j)又出来一个新坑,
  18.     *然后再从前往后找一个比x大的元素(在位置i处)填到坑(位置j)里,位置i处成了一个新坑,这样循环直到i=j,最后将x填到中间这个坑里
  19.     */
  20.     public static int Partition2(int array[],int left,int right)
  21.     {
  22.         int i = left;
  23.         int j = right;
  24.         int x = array[left];
  25.         
  26.         while (i<j)
  27.         {
  28.             while ((i<j)&&(array[j]>x))
  29.                 j--;
  30.             if (i<j)
  31.             {
  32.                 array[i] = array[j];
  33.                 i++;
  34.             }

  35.             while ((i<j)&&(array[i]<x))
  36.                 i++;
  37.             
  38.             if (i<j)
  39.             {
  40.                 array[j] = array[i];
  41.                 j--;
  42.             }
  43.         }
  44.         //退出循环,i==j
  45.         array[i] = x;
  46.         
  47.         return i;
  48.     }
  49.     public static void QuickSort_method(int[] array,int p,int r)
  50.     {
  51.         int q;
  52.         
  53.         if (p<r)
  54.         {
  55.             q = Partition2(array,p,r);
  56.             QuickSort_method(array,p,q-1);
  57.             QuickSort_method(array,q+1,r);
  58.         }
  59.     }
  60.     
  61.   public static void QuickSort_test(int[]array){
  62.     
  63.      QuickSort_method(array,0,array.length-1);
  64.   }
  65.     

  66. }

阅读(677) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~