1.直接挿入ソート
原理:1.全体の間隔はセクション順序付け障害部2に分割され
、ランダムな選択、各時間間隔の最初の要素は、順序付けられた挿入部で適切な位置を選択
考えた:ステップごと点をレコードが値の大きさに応じて、ソートするには、すべてが最後に挿入されたかを知るために行わすでに並んで配列に挿入されています。
コードの実装:
public static void insertSort(int[] array) {
for (int bound = 1; bound < array.length; bound++) {
//bound 下标对应的元素就是待插入元素
//[0,bound)已排序区间
//[bound,array.length)待排序区间
int tmp = array[bound];
int cur = bound-1;
for(; cur >= 0; cur--) {
if(array[cur] > tmp) {
array[cur + 1] = array[cur];
}else {
break;
}
}
array[cur + 1] = tmp;
}
}
時間計算:好ましく:O(n)の最悪:O(N ^ 2)
空間計算量:O(1)
安定性:安定
2.ヒルソート
考え方は次のとおりです。ファイルをソートする、最初の整数を選択グループへのすべてのレコードは、距離の全てが同じサブグループに記録され、各グループの記録がソートされます。次いで、抽出は、グループ化と並べ替え作業を繰り返します。= 1に達すると、統一されたセット内のすべてのレコードがソートされました。
1.ヒルソートは、直接挿入ソート用に最適化されています。
> 1ギャップが予めソートされている場合2.目的は近い整然とした配列に取得することです。ギャップ== 1は、アレイは、密接かつ秩序となっているときに、それはすぐになります。全体このように、最適な結果を達成するために。私たちは、性能比較テストを実現することができます。
イラスト:
のコード:
public static void shellSort(int[] array) {
int gap = array.length;
while( gap > 1) {
insertSortGap(array,gap);
gap = gap / 2;
}
insertSortGap(array,1);
}
private static void insertSortGap(int[] array,int gap) {
for(int bound = 1; bound <array.length;bound++) {
int tmp = array[bound];
int cur = bound - gap;
for (; cur >= 0; cur -= gap) {
if (array[cur] > tmp) {
array[cur + gap] = array[cur];
} else {
break;
}
}
array[cur + gap] = tmp;
}
}
時間複雑:好ましい:O(n)の最悪:O(N ^ 2)
空間の複雑:O(1)
安定性:不安定
3.ダイレクト選択ソート
原理:各障害は、最大間隔(より選択されますまたは最後の(又は最も無秩序前方部に記憶された要素)の最小値)、すべてのデータ要素を排出ソートするまで。
public static void selsctSort(int[] array) {
for(int bound = 0;bound < array.length;bound++) {
for(int cur = bound + 1;cur < array.length; cur++) {
if(array[cur] < array[bound]) {
swap(array,cur,bound);
}
}
}
}
private static void swap(int[] array,int x,int y) {
int tmp = array[x];
array[x] = array[y];
array[y] = tmp;
}
時間の複雑さ:O(N ^ 2)
空間計算量:O(1)
安定性:不安定
4.ヒープソート
原理:基本的な原理は、ソートを選択するのですが、使用中のランダムな間隔の最大数を見つける方法を通過しないように、しかし、最大の数で無秩序なヒープの範囲を選択します。
注:行を昇順で構築杭に、小さなヒープを構築する降順でランク付けしました。
コードの実装:
public static void heapSort(int[] array) {
//1.创建堆
createHeap(array);
//2.循环取出堆顶最大值,放到最后面
for (int i = 0; i < array.length; i++) {
swap(array,0,array.length - i - 1);
shiftDown(array,array.length - i - 1,0);
}
}
private static void shiftDown(int[] array,int size,int index) {
int parent = index;
int child = 2 * parent + 1;
while(child < size) {
if(child + 1 < size
&& array[child + 1] > array[child]) {
child = child + 1;
}
if(array[child] > array[parent]) {
swap(array,child,parent);
}else {
break;
}
parent = child;
child = 2 * parent + 1;
}
}
private static void createHeap(int[] array) {
for(int i = (array.length - 1 - 1) / 2;i >= 0;i--) {
shiftDown(array,array.length,i);
}
}
private static void swap(int[] array,int x,int y) {
int tmp = array[x];
array[x] = array[y];
array[y] = tmp;
}
時間複雑:O(N *ログ(N ))
のスペースの複雑さ:O(1)
安定性:不安定