.example-btn{color:#fff;background-color:#5cb85c;border-color:#4cae4c}.example-btn:hover{color:#fff;background-color:#47a447;border-color:#398439}.example-btn:active{background-image:none}div.example{width:98%;color:#000;background-color:#f6f4f0;background-color:#d0e69c;background-color:#dcecb5;background-color:#e5eecc;margin:0 0 5px 0;padding:5px;border:1px solid #d4d4d4;background-image:-webkit-linear-gradient(#fff,#e5eecc 100px);background-image:linear-gradient(#fff,#e5eecc 100px)}div.example_code{line-height:1.4em;width:98%;background-color:#fff;padding:5px;border:1px solid #d4d4d4;font-size:110%;font-family:Menlo,Monaco,Consolas,"Andale Mono","lucida console","Courier New",monospace;word-break:break-all;word-wrap:break-word}div.example_result{background-color:#fff;padding:4px;border:1px solid #d4d4d4;width:98%}div.code{width:98%;border:1px solid #d4d4d4;background-color:#f6f4f0;color:#444;padding:5px;margin:0}div.code div{font-size:110%}div.code div,div.code p,div.example_code p{font-family:"courier new"}pre{margin:15px auto;font:12px/20px Menlo,Monaco,Consolas,"Andale Mono","lucida console","Courier New",monospace;white-space:pre-wrap;word-break:break-all;word-wrap:break-word;border:1px solid #ddd;border-left-width:4px;padding:10px 15px} 排序算法是《數(shù)據(jù)結(jié)構(gòu)與算法》中最基本的算法之一。排序算法可以分為內(nèi)部排序和外部排序,內(nèi)部排序是數(shù)據(jù)記錄在內(nèi)存中進(jìn)行排序,而外部排序是因排序的數(shù)據(jù)很大,一次不能容納全部的排序記錄,在排序過(guò)程中需要訪問(wèn)外存。常見(jiàn)的內(nèi)部排序算法有:插入排序、希爾排序、選擇排序、冒泡排序、歸并排序、快速排序、堆排序、基數(shù)排序等。以下是快速排序算法:
目前成都創(chuàng)新互聯(lián)已為近千家的企業(yè)提供了網(wǎng)站建設(shè)、域名、虛擬空間、網(wǎng)站托管、服務(wù)器租用、企業(yè)網(wǎng)站設(shè)計(jì)、銀州網(wǎng)站維護(hù)等服務(wù),公司將堅(jiān)持客戶導(dǎo)向、應(yīng)用為本的策略,正道將秉承"和諧、參與、激情"的文化,與客戶和合作伙伴齊心協(xié)力一起成長(zhǎng),共同發(fā)展。
快速排序是由東尼·霍爾所發(fā)展的一種排序算法。在平均狀況下,排序 n 個(gè)項(xiàng)目要 Ο(nlogn) 次比較。在最壞狀況下則需要 Ο(n2) 次比較,但這種狀況并不常見(jiàn)。事實(shí)上,快速排序通常明顯比其他 Ο(nlogn) 算法更快,因?yàn)樗膬?nèi)部循環(huán)(inner loop)可以在大部分的架構(gòu)上很有效率地被實(shí)現(xiàn)出來(lái)。
快速排序使用分治法(Divide and conquer)策略來(lái)把一個(gè)串行(list)分為兩個(gè)子串行(sub-lists)。
快速排序又是一種分而治之思想在排序算法上的典型應(yīng)用。本質(zhì)上來(lái)看,快速排序應(yīng)該算是在冒泡排序基礎(chǔ)上的遞歸分治法。
快速排序的名字起的是簡(jiǎn)單粗暴,因?yàn)橐宦?tīng)到這個(gè)名字你就知道它存在的意義,就是快,而且效率高!它是處理大數(shù)據(jù)最快的排序算法之一了。雖然 Worst Case 的時(shí)間復(fù)雜度達(dá)到了 O(n?),但是人家就是優(yōu)秀,在大多數(shù)情況下都比平均時(shí)間復(fù)雜度為 O(n logn) 的排序算法表現(xiàn)要更好,可是這是為什么呢,我也不知道。好在我的強(qiáng)迫癥又犯了,查了 N 多資料終于在《算法藝術(shù)與信息學(xué)競(jìng)賽》上找到了滿意的答案:
快速排序的最壞運(yùn)行情況是 O(n?),比如說(shuō)順序數(shù)列的快排。但它的平攤期望時(shí)間是 O(nlogn),且 O(nlogn) 記號(hào)中隱含的常數(shù)因子很小,比復(fù)雜度穩(wěn)定等于 O(nlogn) 的歸并排序要小很多。所以,對(duì)絕大多數(shù)順序性較弱的隨機(jī)數(shù)列而言,快速排序總是優(yōu)于歸并排序。
1. 算法步驟
從數(shù)列中挑出一個(gè)元素,稱為 "基準(zhǔn)"(pivot);
重新排序數(shù)列,所有元素比基準(zhǔn)值小的擺放在基準(zhǔn)前面,所有元素比基準(zhǔn)值大的擺在基準(zhǔn)的后面(相同的數(shù)可以到任一邊)。在這個(gè)分區(qū)退出之后,該基準(zhǔn)就處于數(shù)列的中間位置。這個(gè)稱為分區(qū)(partition)操作;
遞歸地(recursive)把小于基準(zhǔn)值元素的子數(shù)列和大于基準(zhǔn)值元素的子數(shù)列排序;
2. 動(dòng)圖演示
代碼實(shí)現(xiàn) JavaScript 實(shí)例 function quickSort ( arr , left , right ) {
var len = arr. length ,
? ? partitionIndex ,
? ? left = typeof left != 'number' ? 0 : left ,
? ? right = typeof right != 'number' ? len - 1 : right ;
if ( left
一趟快速怕序的具體做法是:附設(shè)兩個(gè)指針low和high,他們的初值分別為low和high,設(shè)樞軸記錄的關(guān)鍵字為privotkey,則首先從high所指位置向前搜索找到第一個(gè)關(guān)鍵字小于pivotkey的記錄和樞軸記錄互相交換,然后從low所指向的位置起向后搜索,找到第一個(gè)關(guān)鍵字大于privotkey的記錄和樞軸記錄互相交換,重復(fù)這兩步直至low==high位置.
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class 快速排序_1 {
public static void main(String[] args) throws InterruptedException {
int test[] = {15,23,56,7,13,52,20,7};
new 快速排序_1().qSort(test, 0, test.length-1);
for(int k:test) System.out.println(k);
}
public void qSort(int []array,int low,int high){
if(low
int privot=partition(array,low,high);
qSort(array,low,privot-1);
qSort(array,privot+1,high);
}
}
public int partition(int [] array,int low,int high){
/**
* 選擇 low位置 作為曲軸(支點(diǎn))
*/
int pivot=array[low];
int temp=0;
/**
* 如果 low
*/
while(low
/**
* 先從 high端 開(kāi)始判斷
*/
while(low=pivot) high--;
/**
* 進(jìn)行 置換操作
*/
if(low
array[low]=array[high];
low++;
}
/**
* 從 low 端判斷
*/
while(low
/**
* 進(jìn)行 置換操作
*/
if(low
array[high]=array[low];
high--;
}
}
array[low]=pivot;
return low;
}
}
package temp;
import sun.misc.Sort;
/**
* @author zengjl
* @version 1.0
* @since 2007-08-22
* @Des java幾種基本排序方法
*/
/**
* SortUtil:排序方法
* 關(guān)于對(duì)排序方法的選擇:這告訴我們,什么時(shí)候用什么排序最好。當(dāng)人們渴望先知道排在前面的是誰(shuí)時(shí),
* 我們用選擇排序;當(dāng)我們不斷拿到新的數(shù)并想保持已有的數(shù)始終有序時(shí),我們用插入排序;當(dāng)給出的數(shù)
* 列已經(jīng)比較有序,只需要小幅度的調(diào)整一下時(shí),我們用冒泡排序。
*/
public class SortUtil extends Sort {
/**
* 插入排序法
* @param data
* @Des 插入排序(Insertion Sort)是,每次從數(shù)列中取一個(gè)還沒(méi)有取出過(guò)的數(shù),并按照大小關(guān)系插入到已經(jīng)取出的數(shù)中使得已經(jīng)取出的數(shù)仍然有序。
*/
public int[] insertSort(int[] data) {
1/11頁(yè)
int temp;
for (int i = 1; i data.length; i++) {
for (int j = i; (j 0) (data[j] data[j - 1]); j--) {
swap(data, j, j - 1);
}
}
return data;
}
/**
* 冒泡排序法
* @param data
* @return
* @Des 冒泡排序(Bubble Sort)分為若干趟進(jìn)行,每一趟排序從前往后比較每?jī)蓚€(gè)相鄰的元素的大小(因此一趟排序要比較n-1對(duì)位置相鄰的數(shù))并在
* 每次發(fā)現(xiàn)前面的那個(gè)數(shù)比緊接它后的數(shù)大時(shí)交換位置;進(jìn)行足夠多趟直到某一趟跑完后發(fā)現(xiàn)這一趟沒(méi)有進(jìn)行任何交換操作(最壞情況下要跑n-1趟,
* 這種情況在最小的數(shù)位于給定數(shù)列的最后面時(shí)發(fā)生)。事實(shí)上,在第一趟冒泡結(jié)束后,最后面那個(gè)數(shù)肯定是最大的了,于是第二次只需要對(duì)前面n-1
* 個(gè)數(shù)排序,這又將把這n-1個(gè)數(shù)中最小的數(shù)放到整個(gè)數(shù)列的倒數(shù)第二個(gè)位置。這樣下去,冒泡排序第i趟結(jié)束后后面i個(gè)數(shù)都已經(jīng)到位了,第i+1趟實(shí)
* 際上只考慮前n-i個(gè)數(shù)(需要的比較次數(shù)比前面所說(shuō)的n-1要小)。這相當(dāng)于用數(shù)學(xué)歸納法證明了冒泡排序的正確性
About this application:
This application implements Straight Selection Sort algorithm which is described like this:
If there are N numbers find the minimum and exchange it with the first number then N numbers remained Continue to find the minimum number in the remained N numbers and exchange it with the second number Repeat this until all the numbers are in order
Note: This is SWT application so you need eclipse swt win win x _ v b jar eclipse jface_ I jar mands_ I jar This is for Eclipse
Source Code:
package selection sort;
import java util ArrayList;
import eclipse swt SWT;
import eclipse swt events KeyAdapter;
import eclipse swt events KeyEvent;
import eclipse swt events ModifyEvent;
import eclipse swt events ModifyListener;
import eclipse swt events SelectionAdapter;
import eclipse swt events SelectionEvent;
import eclipse swt layout FormAttachment;
import eclipse swt layout FormData;
import eclipse swt layout FormLayout;
import eclipse swt widgets Button;
import eclipse swt widgets Display;
import eclipse swt widgets Group;
import eclipse swt widgets Label;
import eclipse swt widgets Shell;
import eclipse swt widgets Text;
/**
* This application implements Straight Selection Sort algorithm which means
* get the minimum number from the numbers and exchange it with the first
* number then doing this for other numbers except the first number Repeat
* this until all numbers are in order If you have any suggestion or problem
* please e mail to
*
* @author vivien Data:
*/
public class StraightSelectionSort {
/** The string containing the number wait for sorted */
public String numString = new String();
public Text numText;
public Text resText;
public Button btSort;
public Label errorLabel;
/** The flag to indicate if there is any error for inputed numbers */
public boolean hasError = false;
/** The arrayList containing the double numbers wait for sorted */
public ArrayListDouble numList = new ArrayListDouble();
public static void main(String[] args) {
StraightSelectionSort selectionSort = new StraightSelectionSort();
selectionSort createControl();
}
/**
* Create the control for the interface
*/
public void createControl() {
Display display = new Display();
Shell shell = new Shell(display);
shell setBounds( );
// Set Title
shell setText( Straight selection sort );
FormLayout layout = new FormLayout();
shell setLayout(layout);
FormData fd = new FormData();
// The Start Sort button
btSort = new Button(shell SWT NONE | SWT CENTER);
btSort setText( Start Sort );
fd = new FormData();
fd height = ;
fd top = new FormAttachment( );
fd left = new FormAttachment( );
btSort setLayoutData(fd);
// The Input numbers group
Group numGroup = new Group(shell SWT NONE);
numGroup setText( Input numbers: );
numGroup setLayout(layout);
fd = new FormData();
fd top = new FormAttachment( );
fd left = new FormAttachment( );
fd right = new FormAttachment( );
fd bottom = new FormAttachment(btSort );
numGroup setLayoutData(fd);
// Label for input numbers
Label numLabel = new Label(numGroup SWT WRAP);
numLabel
setText( Please input the numbers you want to sort: (Note: Numbers need to be seperated by space) );
fd = new FormData();
fd top = new FormAttachment( );
fd left = new FormAttachment( );
fd right = new FormAttachment( );
numLabel setLayoutData(fd);
// Text for input numbers
numText = new Text(numGroup SWT BORDER | SWT MULTI | SWT V_SCROLL
| SWT WRAP);
numText setToolTipText( Numbers need to be seperated by space );
fd = new FormData();
fd top = new FormAttachment(numLabel );
fd left = new FormAttachment( );
fd right = new FormAttachment( );
fd bottom = new FormAttachment( );
numText setLayoutData(fd);
// The results group
Group resGroup = new Group(shell SWT NONE);
resGroup setText( The results: );
resGroup setLayout(layout);
fd = new FormData();
fd top = new FormAttachment(btSort );
fd left = new FormAttachment( );
fd right = new FormAttachment( );
fd bottom = new FormAttachment( );
resGroup setLayoutData(fd);
// Label for results
Label resLabel = new Label(resGroup SWT WRAP);
resLabel
setText( The results after sorted are: (Note: Results are seperated by space) );
fd = new FormData();
fd top = new FormAttachment( );
fd left = new FormAttachment( );
fd right = new FormAttachment( );
resLabel setLayoutData(fd);
// Text for results
resText = new Text(resGroup SWT BORDER | SWT MULTI | SWT V_SCROLL
| SWT WRAP);
resText setToolTipText( Results are seperated by space );
resText setEditable(false);
fd = new FormData();
fd top = new FormAttachment(resLabel );
fd left = new FormAttachment( );
fd right = new FormAttachment( );
fd bottom = new FormAttachment( );
resText setLayoutData(fd);
// Label for showing error message
errorLabel = new Label(shell SWT NONE);
fd = new FormData();
fd top = new FormAttachment( );
fd left = new FormAttachment( );
fd right = new FormAttachment( );
fd bottom = new FormAttachment( );
errorLabel setLayoutData(fd);
errorLabel setForeground(display getSystemColor(SWT COLOR_RED));
// Listen to the numText change
numText addModifyListener(new ModifyListener() {
@Override
public void modifyText(ModifyEvent e) {
numString = numText getText() trim();
hasError = false;
}
});
// If press Return focus go to Start Sort button and start sort
numText addKeyListener(new KeyAdapter() {
@Override
public void keyPressed(KeyEvent e) {
if (e keyCode == \r ) {
e doit = false;
btSort setFocus();
startSort();
}
}
});
// Listen to the button selection
btSort addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
startSort();
}
});
shell open();
while (!shell isDisposed()) {
if (!display readAndDispatch())
display sleep();
}
display dispose();
}
/**
* Get double values from string
*/
public void getDoubleFromString() {
int index = ;
// Split string using space
String[] splitedNumbers = numString split( );
if (numList size() != )
// Clear the arrayList for last used
numList clear();
for (int i = ; i splitedNumbers length; i++) {
if (splitedNumbers[i] trim() length() != ) {
try {
numList add(index++ Double valueOf(splitedNumbers[i]));
} catch (NumberFormatException e) {
setErrorMessage( Please input the correct numbers );
hasError = true;
break;
}
}
}
}
/**
* Start sort the string containing numbers waited for sort
*/
public void startSort() {
if (numString != null)
if (numString trim() length() != ) {
getDoubleFromString();
startStraightSelectionSort();
setResults();
} else {
setErrorMessage( Please input numbers );
hasError = true;
}
}
/**
* Set the results to the results group
*/
public void setResults() {
if (!hasError) {
String resString = new String();
for (int i = ; i numList size(); i++)
if (i != numList size() )
resString = resString + numList get(i) + ;
else
// If be the last string
resString = resString + numList get(i);
resText setText(resString);
// Clear errorLabel
errorLabel setText( );
}
}
/**
* Sort the numbers using Straight selection Sort algorithm
*/
public void startStraightSelectionSort() {
int minPosition = ;
for (int j = ; j numList size() ; j++) {
minPosition = j;
for (int i = j + ; i numList size(); i++) {
if (numList get(i) numList get(minPosition)) {
minPosition = i;
}
}
if (minPosition != j) {
// Exchange the minimum with the first number of the numbers
// waited for sort
double temp = numList get(j);
numList set(j numList get(minPosition));
numList set(minPosition temp);
}
}
}
/**
* Set the error message on the error Label
*
* @param errorString
*??????????? The string used for set on the errorLabel
*/
public void setErrorMessage(String errorString) {
errorLabel setText(errorString);
// Clear the text of results
resText setText( );
hasError = true;
}
}
Black box Test Case:
)????? All numbers are zero:
分享文章:直接排序java代碼 java直接排序算法
URL分享:http://www.chinadenli.net/article26/dosiicg.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供ChatGPT、營(yíng)銷型網(wǎng)站建設(shè)、全網(wǎng)營(yíng)銷推廣、定制開(kāi)發(fā)、軟件開(kāi)發(fā)、移動(dòng)網(wǎng)站建設(shè)
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來(lái)源: 創(chuàng)新互聯(lián)