快速排序Java實現

來源:互聯網
上載者:User

第一、演算法原理

針對數組中的一個數(這個數叫做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);

}

}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.