归并实现原理:
尽可能的将一组数据拆分成两个元素相等的子组,并对每一个子组继续拆分,直到拆分后的每一个子组的元素个数是1为止。将相邻的两个子组进行合并成一个有序的大组。不断重复步骤 2 和 步骤 3, 直到最终只有一个组为止。
归并排序算法实现:(稳定排序)
public static void main(String
[] args
) {
int[] arr
= {8, 4, 5, 7, 1, 3, 6, 2};
sort(arr
);
for (int i
: arr
) {
System
.out
.print(i
+"\t");
}
}
private static int[] assist
;
private static boolean less(int v
, int w
) {
return v
< w
;
}
private static void exch(int[] a
, int i
, int j
) {
int temp
;
temp
= a
[i
];
a
[i
] = a
[j
];
a
[j
] = temp
;
}
public static void sort(int[] a
) {
assist
= new int[a
.length
];
int lo
= 0;
int hi
= a
.length
- 1;
sort(a
, lo
, hi
);
}
private static void sort(int[] a
, int low
, int height
) {
if (height
<= low
) {
return;
}
int mid
= low
+ (height
- low
) / 2;
sort(a
, low
, mid
);
sort(a
, mid
+ 1, height
);
merge(a
, low
, mid
, height
);
}
private static void merge(int[] a
, int low
, int mid
, int height
) {
int i
= low
;
int p1
= low
;
int p2
= mid
+ 1;
while (p1
<= mid
&& p2
<= height
) {
if (less(a
[p1
], a
[p2
])) {
assist
[i
++] = a
[p1
++];
} else {
assist
[i
++] = a
[p2
++];
}
}
while (p1
<= mid
) {
assist
[i
++] = a
[p1
++];
}
while (p2
<= height
) {
assist
[i
++] = a
[p2
++];
}
for (int index
= low
; index
<= height
; index
++) {
a
[index
] = assist
[index
];
}
}
转载请注明原文地址:https://blackberry.8miu.com/read-34832.html