Selection sort

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
import java.util.Random;

public class Selection_sort {
// ---------------------------------------------simple selection sorting
public static void selectionSort(int[] arr) {
for (int i = 0; i < arr.length - 1; i++) {
int min = i;
for (int j = i + 1; j < arr.length; j++) {
if (arr[j] < arr[min]) {
min = j;
}
}
int tmp = arr[min];
arr[min] = arr[i];
arr[i] = tmp;
}
}

// ---------------------------------------------heap sorting
public static void HeapSort(int[] nums) {
// Build heap (rearrange array)
int n = nums.length;
for (int i = n / 2 - 1; i >= 0; i--){
heapify_recursive(nums, i, n);
}
// One by one extract an element from heap
for (int i = n - 1; i > 0; i--) {
// Move current root to end
int tmp = nums[0];
nums[0] = nums[i];
nums[i] = tmp;
// call max heapify on the reduced heap
heapify_recursive(nums, 0, i);
}
}

// To heapify a subtree rooted with node i which is
// an index in arr[]. n is size of heap
public static void heapify_recursive(int[] arr, int i, int n) {
int largest = i; // Initialize largest as root
int l = 2 * i + 1; // left = 2*i + 1
int r = 2 * i + 2; // right = 2*i + 2

// If left child is larger than root
if (l < n && arr[l] > arr[largest])
largest = l;

// If right child is larger than largest so far
if (r < n && arr[r] > arr[largest])
largest = r;

// If largest is not root
if (largest != i) {
int swap = arr[i];
arr[i] = arr[largest];
arr[largest] = swap;

// Recursively heapify the affected sub-tree
heapify_recursive(arr, largest, n);
}
}
/*
// To heapify a subtree rooted with node i which is
// an index in arr[]. n is size of heap
public static void HeapAdjust(int[] num, int i, int n) {
int tmp = num[i];
// 根据完全二叉树的性质可知道每一个序号对应的子节点以及双亲节点
for (int j = 2 * i + 1; j < n; j = 2 * j + 1) {
// j指向数值较大的节点
if (j + 1 < n && num[j] < num[j + 1]) j = j + 1;
// 如果调整节点大于其子节点最大的值则无需调整
if (tmp > num[j]) break;
// 如果小于则将子节点移动到根节点位置,如果还存在子节点则继续判断调整位置的子节点,准备继续向下 调整节点
num[i] = num[j];
i = j;
}
// 最后插入数据
num[i] = tmp;
}*/
// *********************************************
public static void main(String[] args) {
int[] arr1 = new Random().ints(20, 1,100).toArray();
selectionSort(arr1);
System.out.println("\nsimple selection sort: ");
for (int i : arr1) System.out.print(i+",");
System.out.println("\n");

int[] arr2 = new Random().ints(20, 1,100).toArray();
HeapSort(arr2);
System.out.println("heapSort: ");
for (int i : arr2) System.out.print(i+",");
System.out.println("\n");
}
}
0%