Skip to content

Commit 36aea2e

Browse files
committed
增加了对排序算法稳定性判断
1 parent 7bc7130 commit 36aea2e

1 file changed

Lines changed: 12 additions & 6 deletions

File tree

  • src/main/java/cn/byhieg/algorithmtutorial

src/main/java/cn/byhieg/algorithmtutorial/Sort.java

Lines changed: 12 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ public class Sort {
1010
* 选择排序,每一轮排序,选择数组中数字最小的那一个放到指定的位置上。
1111
* 时间复杂度o(n^2),无论数组顺序如何都要选择一个最小的值,因为数组的是否有序,不影响时间复杂度
1212
* 空间复杂度o(1)
13-
*
13+
* 不稳定排序
1414
* @param nums
1515
*/
1616
public void chooseSort(int[] nums) {
@@ -33,13 +33,14 @@ public void chooseSort(int[] nums) {
3333
* 直接插入排序,每一轮排序,都是在i坐标之前,包括i坐标的序列是有序的,但是并不是最终的排序位置。
3434
* 时间复杂度o(n^2),对于第二重循环,只会在非有序的环境下才会执行每个元素后移,因此针对有序的数组,时间复杂度最好的情况是o(N)。
3535
* 空间复杂度o(1)
36-
*
36+
* 稳定排序
3737
* @param nums
3838
*/
3939
public void insertDirectlySort(int[] nums) {
4040
int length = nums.length;
4141
for (int i = 1; i < length; i++) {
4242
for (int j = i; j > 0; j--) {
43+
//这一步导致该算法是稳定排序
4344
if (nums[j] < nums[j - 1]) {
4445
int tmp = nums[j - 1];
4546
nums[j - 1] = nums[j];
@@ -83,13 +84,14 @@ public void insertBinarySort(int[] nums) {
8384
* 这种实现是按照算法定义的,但是效率是最低的
8485
* 时间复杂度o(n^2)
8586
* 空间复杂度o(1)
86-
*
87+
* 稳定排序
8788
* @param nums
8889
*/
8990
public void bubbleSort1(int[] nums) {
9091
int length = nums.length;
9192
for (int i = 1; i < length; i++) {
9293
for (int j = 0; j < length - i; j++) {
94+
//这一步导致该算法是稳定排序
9395
if (nums[j] > nums[j + 1]) {
9496
int tmp = nums[j];
9597
nums[j] = nums[j + 1];
@@ -126,7 +128,7 @@ public void bubbleSort2(int[] nums) {
126128
* 快速排序,选定一个切分元素,每一轮排序后,都保证切分元素之前的元素都小于切分元素,切分元素之后的元素都大于切分元素
127129
* 时间复杂度o(NlgN)
128130
* 空间复杂度o(lgN)
129-
*
131+
* 不稳定排序
130132
* @param nums
131133
*/
132134
public void quickSort(int[] nums) {
@@ -192,12 +194,16 @@ public int partition(int[] nums, int low, int high) {
192194
* 时间复杂度:o(NlgN)
193195
* 空间复杂度: o(1)
194196
* 这是小顶堆的排序,所以nums数组最后是降序的
197+
* 不稳定,不稳定的原因在建堆的时候,就可能把相同元素的位置换了,比如两个相同元素在不同的子树上
195198
* @param nums
196199
*/
197200
public void heapSort(int[] nums) {
198201
int length = nums.length;
199-
for (int i = 0; i < length; i++) {
200-
swim(nums, i);
202+
// for (int i = 0; i < length; i++) {
203+
// swim(nums, i);
204+
// }
205+
for (int i = length / 2 ; i >= 0;i--) {
206+
sink(nums,i,length);
201207
}
202208
while (length > 0) {
203209
int temp = nums[0];

0 commit comments

Comments
 (0)