# 2. Bubble Sort (Bubble Sort)

## 2.1Baseline

```    static void bubbleSort1(Integer[] array) {
for (int end = array.length - 1; end > 0; end--) {
for (int begin = 1; begin <= end; begin++) {
if (array[begin] < array[begin - 1]) {
int tmp = array[begin];
array[begin] = array[begin - 1];
array[begin - 1] = tmp;
}
}
}
}```
View Code

## 2.2 Bubble sort - optimization 1

```    static void bubbleSort2(Integer[] array) {
for (int end = array.length - 1; end > 0; end--) {
boolean sorted = true;
for (int begin = 1; begin <= end; begin++) {
if (array[begin] < array[begin - 1]) {
int tmp = array[begin];
array[begin] = array[begin - 1];
array[begin - 1] = tmp;
sorted = false;
}
}
if (sorted) break;
}
}```
View Code

## 2.3 bubble sort - 2 Optimization

```    static  void bubbleSort3 (Integer [] Array) {
for ( int End be array.length = -. 1; End> 0; end-- ) {
// initial value sortedIndex useful when fully ordered array
int sortedIndex =. 1 ;
for ( int the begin =. 1; the begin <= End; the begin ++ ) {
IF (Array [the begin] <Array [the begin -. 1 ]) {
int tmp = Array [the begin];
Array [the begin] = Array [the begin -. 1 ];
Array [the begin -. 1] = tmp;
sortedIndex= begin;
}
}
end = sortedIndex;
}
}```
View Code

# 3. Selection Sort (Selection Sort)

## 3.1Baseline

```    static void selectionSort(Integer[] array) {
for (int end = array.length - 1; end > 0; end--) {
int maxIndex = 0;
for (int begin = 1; begin <= end; begin++) {
if (array[maxIndex] <= array[begin]) {
maxIndex = begin;
}
}
int tmp = array[maxIndex];
array[maxIndex] = array[end];
array[end] = tmp;
}

// 8 10 9 10
}```
View Code

## 3.3 heapsort achieve

```package com.mj.sort.cmp;

import com.mj.sort.Sort;

public class HeapSort<T extends Comparable<T>> extends Sort<T> {
private int heapSize;

@Override
protected void sort() {
// 原地建堆
heapSize = array.length;
for (int i = (heapSize >> 1) - 1; i >= 0; i--) {
siftDown(i);
}

while (heapSize > 1) {
// 交换堆顶元素和尾部元素
swap(0, --HEAPSIZE);

// for 0 position siftDown (recovery properties of the stack)
siftDown (0 );
}
}

Private  void siftDown ( int index) {
T Element = Array [index];

int Half = HEAPSIZE >>. 1 ;
the while (index <Half) { // index must be non-leaf node
// default is left with a parent node than
int the childIndex = (index <<. 1) +. 1 ;
T Child = Array [the childIndex];

int rightIndex the childIndex + =. 1 ;
// Right child node left child than big
if (rightIndex < heapSize &&
cmp(array[rightIndex], child) > 0) {
child = array[childIndex = rightIndex];
}

// 大于等于子节点
if (cmp(element, child) >= 0) break;

array[index] = child;
index = childIndex;
}
array[index] = element;
}
}```
View Code

### Guess you like

Origin www.cnblogs.com/ggnbnb/p/12539761.html
Recommended
Ranking
Daily