package algorihtm;
/*
简单选择排序(每次找出最小的数据放到前面)
堆排序(大根堆)
*/
public class SelectionSort {
private int[] array;
int len;
public SelectionSort(int[] array) {
this.array = array;
len = array.length;
}
public void display() {
try {
for (int i : array) {
System.out.print(i + " ");
}
System.out.println();
} catch (Exception e) {
e.printStackTrace();
}
}
//每次找出最小的数,与array[i]交换
public void basicSelection() {
for (int i = 0; i < len; i++) {
int pos = i;
for (int j = i + 1; j < len; j++) {
if (array[j] < array[pos]) {
pos = j;
}
}
if (pos != i) {
array[i] = array[i] + array[pos];
array[pos] = array[i] - array[pos];
array[i] = array[i] - array[pos];
}
}
}
//调整堆
/*
大根堆:
对pos结点调整
pos与其左右孩子进行比较,若其孩子有大于array[pos]的,将array[pos]与较大的孩子对换
*/
public void adjustHeap(int heapSize, int pos) {
int left = 2 * pos + 1;
int right = 2 * pos + 2;
int largest = pos;
if (left < heapSize && array[left] > array[pos]) {
largest = left;
}
if (right < heapSize && array[right] > array[largest]) {
largest = right;
}
if (largest != pos) {
array[largest] += array[pos];
array[pos] = array[largest] - array[pos];
array[largest] = array[largest] - array[pos];
adjustHeap(heapSize, largest);
}
}
//
public void buildHeap(int heapSize) {
int i = heapSize / 2 - 1;
while (i >= 0) {
adjustHeap(heapSize, i);
i--;
}
}
//
public void heapSort() {
int heapSize = len;
buildHeap(heapSize);
System.out.println("建立大根堆:");
for(int i=0;i<len;i++){
System.out.print(array[i]+" ");
}
System.out.println();
/*此时 array是具有大根堆结构特性的数组
array[0]最大,将array[0]与末尾array[i]交换,末尾最大
但此时由于array[0] ,不符合大根堆特性,所以对其进行调整
调整结束后 array[0]是数组 0~i-1 中最大的,将array[0]与array[i-1]交换
*/
for (int i = heapSize - 1; i > 0; i--) {
array[0] += array[i];
array[i] = array[0] - array[i];
array[0] = array[0] - array[i];
heapSize--;
adjustHeap(heapSize, 0);
}
}
public static void main(String[] args) {
int[] array = new int[]{5, 2, 6, 9, 0, 1};
SelectionSort obj = new SelectionSort(array);
obj.display();
//obj.basicSelection();
obj.heapSort();
obj.display();
}
}
选择排序、堆排序
猜你喜欢
转载自blog.csdn.net/weixin_42129373/article/details/80186764
今日推荐
周排行