冒泡排序BubbleSort
时间复杂度:O(n^2)
稳定性:稳定
public class BubbleSort {
public BubbleSort(int[] a) {
// TODO Auto-generated constructor stub
int s = 0;
for(int i = 0; i < a.length - 1; i++) {
for(int j = 0; j < a.length - 1; j++) {
if(a[j + 1] < a[j]) {
s = a[j + 1]; a[j + 1] = a[j]; a[j] = s;
}
}
}
}
}
选择排序SelectSort
时间复杂度:O(n^2)
稳定性:不稳定
public class SelectSort {
public SelectSort(int[] a) {
// TODO Auto-generated constructor stub
int s = 0;
for(int i = 0; i < a.length - 1; i++) {
for(int j = i + 1; j < a.length; j++) {
if(a[j] < a[i]) {
s = a[j]; a[j] = a[i]; a[i] = s;
}
}
}
}
}
插入排序InsertSort
public class InsertSort {
public InsertSort(int[] a) {
// TODO Auto-generated constructor stub
int s = 0;
for(int i = 1; i < a.length; i++) {
s = a[i];
int j = i;
for(; j > 0; j--) {
if(s < a[j - 1]) {
a[j] = a[j - 1];
} else break;
}
a[j] = s;
}
}
public InsertSort(int[] a, boolean sign) {
// TODO Auto-generated constructor stub
int s = 0;
for(int i = 1; i < a.length; i++) {
s = a[i];
int j = i - 1;
while(j >= 0 && a[j] > s) {
a[j + 1] = a[j];
j -= 1;
}
a[j + 1] = s;
}
}
}
归并排序MergeSort
public class MergeSort {
public MergeSort(int[] a) throws Exception {
// TODO Auto-generated constructor stub
merge(a, 0, a.length - 1);
}
public static void merge(int[] a, int i, int j) throws Exception {
if(i < j) {
merge(a, i, (i + j)/2);
merge(a, (i + j) / 2 + 1, j);
sort(a, i, (i + j) / 2, j);
}
}
public static void sort(int[] a, int i, int k, int j) throws Exception {
int x = k - i + 1;
int y = j - k;
int b[] = new int[x];
int c[] = new int[y];
for(int n = 0; n < x; n++) {
b[n] = a[n + i];
}
for(int n = 0; n < y; n++) {
c[n] = a[n + k + 1];
}
int s = 0, t = 0;
for(int n = 0; n < x + y; n++) {
if(t >= y || s < x && b[s] <= c[t]) {
a[n + i] = b[s];
s++;
} else if(s >= x || t < y && b[s] > c[t]) {
a[n + i] = c[t];
t++;
} else {
throw new Exception();
}
}
}
}
快速排序QuickSort
public class QuickSort {
public QuickSort(int a[]) {
quickSort(a, 0, a.length - 1);
}
public void quickSort(int a[], int l, int r) {
if(l < r) {
int i = l;
int j = r;
int x = a[l];
while(i < j) {
while(i < j && a[j] >= x) {
j--;
}
if(i < j) {
a[i++] = a[j];
}
while(i < j && a[i] < x) {
i++;
}
if(i < j) {
a[j--] = a[i];
}
}
a[i] = x;
quickSort(a, l, i - 1);
quickSort(a, i + 1, r);
}
}
}
堆排序HeapSort
public class HeapSort {
public HeapSort(int a[]) {
// TODO Auto-generated constructor stub
buildHeap(a);
int heapSize = a.length - 1;
int s;
while(heapSize != 1) {
s = a[1];
a[1] = a[heapSize];
a[heapSize] = s;
heapSize -= 1;
balance(a, 1);
}
}
public void buildHeap(int a[]) {
for(int i = 1; i < (a.length - 1) / 2; i++) {
balance(a, i);
}
}
public void balance(int a[], int i) {
int heapSize = a.length - 1;
int largest = i;
if(i * 2 < heapSize && a[i * 2] > largest) {
largest = i * 2;
}else if(i * 2 + 1 < heapSize && a[i * 2 + 1] > largest) {
largest = i * 2 + 1;
}
if(largest != i) {
int s = a[i];
a[i] = a[largest];
a[largest] = s;
balance(a, largest);
}
}
}