希爾排序和高速排序

//希爾排序
在直接插入排序算法中,每次插入一個數,使有序序列僅僅添加1個節點,並且對插入下一個數沒有提供不論什麼幫助。
假設比較相隔較遠距離(稱爲增量)的數,使得數移動時能跨過多個元素,則進行一次比較就可能消除多個元素交換。
D.L.shell於1959年在以他名字命名的排序算法中實現了這一思想。算法先將要排序的一組數按某個增量d分紅若干組,
每組中記錄的下標相差d.對每組中全部元素進行排序,而後再用一個較小的增量對它進行,在每組中再進行排序。
當增量減到1時,整個要排序的數被分紅一組,排序完畢

public class TestXe {
public static int[] a = { 10, 32, 1, 9, 5, 8, 88, 12, 0, 4, 3, 66 }; // 預設數據數組
public static void main(String args[]) {
int i; // 循環計數變量
int Index = a.length;// 數據索引變量
for (i = 0; i < Index - 1; i++)
System.out.printf("%3s ", a);
System.out.println("");
ShellSort(Index - 1); // 選擇排序
for (i = 0; i < Index - 1; i++)
System.out.printf("%3s ", a);
System.out.println("");
}

public static void ShellSort(int Index) {
int i, j, k; // 循環計數變量
int Temp; // 暫存變量
boolean Change; // 數據是否改變
int DataLength; // 切割集合的間隔長度
int Pointer; // 進行處理的位置
DataLength = (int) Index / 2; // 初始集合間隔長度
while (DataLength != 0) // 數列仍可進行切割
{
// 對各個集合進行處理
for (j = DataLength; j < Index; j++) {
Change = false;
Temp = a[j]; // 暫存Data[j]的值,待交換值時用
Pointer = j - DataLength; // 計算進行處理的位置
// 進行集合內數值的比較與交換值
while (Temp < a[Pointer] && Pointer >= 0 && Pointer <= Index) {
a[Pointer + DataLength] = a[Pointer];
// 計算下一個欲進行處理的位置
Pointer = Pointer - DataLength;
Change = true;
if (Pointer < 0 || Pointer > Index)
break;
}
// 與最後的數值交換
a[Pointer + DataLength] = Temp;
if (Change) {
// 打印眼下排序結果
System.out.print("排序結果: ");
for (k = 0; k < Index; k++)
System.out.printf("%3s ", a[k]);
System.out.println("");
}
}
DataLength = DataLength / 2; // 計算下次切割的間隔長度
}
}

}算法

--------------------------------------------------------------shell

經過一趟排序將要排序的數據切割成獨立的兩部分,當中一部分的所有數據都比另一部分的所有數據都要小,而後再按此方法對這兩部分數據分別進行高速排序,整個排序過程可以遞歸進行,以此達到整個數據變成有序序列。①以第一個keyword K 1 爲控制字,將 [K 1 ,K 2 ,…,K n ] 分紅兩個子區,使左區所有keyword小於等於 K 1 ,右區所有keyword大於等於 K 1 ,最後控制字居兩個子區中間的適當位置。在子區內數據尚處於無序狀態。 ②把左區做爲一個整體,用①的步驟進行處理,右區進行一樣的處理。(即遞歸)③反覆第①、②步,直到左區處理完成。數組

public class QuickSort {
/**
* 高速排序,對整數型數組o進行
*/
public static void quiteSort(int[] o, int low, int hight) {
if (low < hight) {
int povitePosition = adjust(o, low, hight);
quiteSort(o, low, povitePosition - 1);
quiteSort(o, povitePosition + 1, hight);
}
}

/**
* 進行調整
*/
private static int adjust(int[] o, int low, int hight) {// 選定樞軸爲low所相應的值
int pivote = o[low];
while (low < hight) {
while (hight > low && compare(pivote, o[hight]) <= 0) {// 高位找到比povite大,則符合要求,繼續尋找
hight--;
}
o[low] = o[hight];
while (low < hight && compare(pivote, o[low]) >= 0) { // 低位開始找到比povite小,符合要求,繼續尋找
low++;
}
o[hight] = o[low];
}
o[low] = pivote;
return low;
}

/**
* @param num1  減數
* @param num2  被減數
*/
private static int compare(int num1, int num2) {
return num1 - num2;
}

public static void main(String[] args) {
int[] i = { 26, 53, 48, 15, 13, 46, 32, 18, 16 };
quiteSort(i, 0, i.length - 1);
for (int ii : i) {
System.out.print(ii + " ");
}
}
}
ui

相關文章
相關標籤/搜索