您的位置:首页 > 编程语言 > Java开发

快速排序Java实现

2012-09-20 18:55 357 查看
第一、算法原理

针对数组中的一个数(这个数叫做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);

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: