算法排序

package com.sdcet.SunFa;


import java.util.Random;


public class Sort {


// 冒泡排序
public void bubbling(int[] a) {
int len = a.length;
for (int i = 0; i < len - 1; i++) {
for (int j = len - 1; j > i; j--) {
if (a[j] < a[j - 1]) {
int t = a[j];
a[j] = a[j - 1];
a[j - 1] = t;
}
}
}
}


// 交换法
public void change(int[] a) {
int len = a.length;
for (int i = 0; i < len - 1; i++) {
for (int j = i + 1; j < len; j++) {
if (a[i] > a[j]) {
int t = a[i];
a[i] = a[j];
a[j] = t;
}
}
}
}


// 选择法
public void choose(int[] a) {
int len = a.length;
for (int j = 0; j < len - 1; j++) {
int min = a[j];
int pos = j;
for (int i = j + 1; i < len; i++) {
if (a[i] < min) {
min = a[i];
pos = i;
}
}
a[pos] = a[j];
a[j] = min;
}


}


// 插入法
public void insert(int[] a) {
int len = a.length;
for (int pos = 1; pos < len; pos++) {
int t = a[pos];
int i = pos - 1;
while (i >= 0 && a[i] > t) {
a[i + 1] = a[i];
i--;
}
a[i + 1] = t;
}
}


// 快速排序
public void quick(int[] a, int start, int end) {
int mid = (start + end) / 2;
int i = start;
int j = end;
while (i <= j) {
// 从左边找比参照值大的
while (a[i] < a[mid]) {
i++;
}
// 从右边找比参照值小的


while (a[j] > a[mid]) {
j--;
}


// 交换
if (i <= j) {
int t = a[i];
a[i] = a[j];
a[j] = t;
j--;
i++;
}
}


if (start <= j) {
quick(a, start, j);
}


if (i <= end) {
quick(a, i, end);
}
}


public static void main(String[] args) {


int[] a = new int[50000];
int[] b = new int[50000];
int[] c = new int[50000];
int[] d = new int[50000];
int[] e = new int[50000];


for (int i = 0; i < 50000; i++) {
a[i] = new Random().nextInt();
}


System.arraycopy(a, 0, b, 0, 50000);
System.arraycopy(a, 0, c, 0, 50000);
System.arraycopy(a, 0, d, 0, 50000);
System.arraycopy(a, 0, e, 0, 50000);


long start = System.currentTimeMillis();
new Sort().bubbling(a);
long end = System.currentTimeMillis();
System.out.println("冒泡花了:" + (end - start));


start = System.currentTimeMillis();
new Sort().change(b);
end = System.currentTimeMillis();
System.out.println("交换花了:" + (end - start));


start = System.currentTimeMillis();
new Sort().choose(c);
end = System.currentTimeMillis();
System.out.println("选择花了:" + (end - start));


start = System.currentTimeMillis();
new Sort().insert(d);
end = System.currentTimeMillis();
System.out.println("插入花了:" + (end - start));


start = System.currentTimeMillis();
new Sort().quick(e, 0, e.length - 1);
end = System.currentTimeMillis();
System.out.println("快排花了:" + (end - start));


int[] f = { 6, 10, 7, 8, 4 };
new Sort().quick(f, 0, f.length - 1);


for (int i = 0; i < f.length; i++) {
System.out.println(f[i]);
}
}
}

你可能感兴趣的:(算法排序)