快速排序Java实现

第一、算法原理

针对数组中的一个数(这个数叫做pivot),将这个数组划分成两个部分:左边的每个元素都比pivot小;右边的每个元素都比pivot大。然后,再分别在左右两个部分递归地进行这种划分的操作。

如此说比较笼统,在这个大方向上实际上是隐含着两个重要的地方:

1、如何确定pivot

2、如何划分

至于如何确定pivot这点先默认认为是取数组中的第一个元素,在下文将会针对取pivot,提出提高效率的方案。而至于如何划分,这点需要在这里马上说明。

在这里的划分,是基于两个元素的位置交换实现的。而需要互换的两个元素有这样的特点,就左边的元素的值比pivot的要大,而右边的元素的值比pivot要小。

代码实现+解释(解释使用英文,因为想进外企,努力训练英文中)

public class SortTest<E extends Comparable<E>> {

public ArrayList<E> quicksort(ArrayList<E> arraylist) {

ArrayList<E> ret = null;

if (arraylist == null || arraylist.size() == 0) {

throw new IllegalArgumentException();

}

subquicksort(0, arraylist.size() - 1, arraylist);

ret = arraylist;

return ret;

}

public void subquicksort(int begin, int end, ArrayList<E> arraylist) {

ArrayList<E> ret = null;

if (begin < end) {

// by default,use the first item of the array as the pivot

E pivotkey = arraylist.get(begin);

// i is the monitor of the current left-side item

int i = begin;

//j is the right-side monitor

//why set j as "end+1" not end?

//because in the coming snippet:

//while (j > begin && arraylist.get(--j).compareTo(pivotkey) >= 0)

//;

//If we do not do like that way,like,we use j++ instead,we will get

//the wrong index afterward.

int j = end + 1;

while (true) {

//We can look over the items that are smaller than pivot and 

//let the i come to item that is bigger than pivot.

while (i < end && arraylist.get(++i).compareTo(pivotkey) <= 0)

;

//It's just like the last sentence

while (j > begin && arraylist.get(--j).compareTo(pivotkey) >= 0)

;

if (i >= j) {// let the j be the position for the pivot

break;

else {

swap(i, j, arraylist);

}

}

//the j th item still stores the value smaller than pivot. 

swap(begin, j, arraylist);

//recurse

subquicksort(begin, j - 1, arraylist);

subquicksort(j + 1, end, arraylist);

}

}

public void swap(int i, int j, ArrayList<E> arraylist) {

E temp;

temp = arraylist.get(j);

arraylist.set(j, arraylist.get(i));

arraylist.set(i, temp);

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值