一、冒泡排序
package pku.ss.datastructure.Sort;
public class BubbleSort {
public static void main(String[] args) {
int max = 1000000;
ArrayBubble arr = new ArrayBubble(max);
long startTime = System.currentTimeMillis();
for (int j = 0; j 0; outer--)
for (int j = 0; j array[j + 1]) {
swap(j, j + 1);
}
}
}
private void swap(int x, int y) {
double temp;
temp = array[x];
array[x] = array[y];
array[y] = temp;
}
}
二、选择排序
package pku.ss.datastructure.Sort;
public class SelectSort {
public static void main(String[] args) {
int max = 1000000;
ArraySel arr = new ArraySel(max);
long startTime = System.currentTimeMillis();
for (int j = 0; j < max; j++) {
double element = (double) (java.lang.Math.random() * (max - 1));
arr.insert(element);
}
long endTime = System.currentTimeMillis();
System.out.println("Sort time: " + (endTime - startTime) + " ms");
}
}
/** ***************************************** */
class ArraySel {
private double[] a;
private int nElement;
//--------------------------------------------------------
public ArraySel(int max) {
a = new double[max];
nElement = 0;
}
//--------------------------------------------------------
public void insert(double element) {
a[nElement] = element;
nElement++;
}
//--------------------------------------------------------
public void display() {
for (int i = 0; i < nElement; i++)
System.out.print(a[i] + " ");
System.out.println();
}
//--------------------------------------------------------
public void selectSort() {
int out, in, min;
for (out = 0; out < nElement - 1; out++) {
min = out;
for (in = out + 1; in < nElement; in++) {
if (a[in] < a[min]) {
min = in;
}
}
if(min!=out)
swap(min, out);
}
}
//--------------------------------------------------------
private void swap(int x, int y) {
double temp;
temp = a[x];
a[x] = a[y];
a[y] = temp;
}
}
三、插入排序
package pku.ss.datastructure.Sort;
public class InsertionSort {
public static void main(String[] args) {
int max = 1000000;
ArrayIns arr = new ArrayIns(max);
long startTime = System.currentTimeMillis();
for (int j = 0; j < max; j++) {
double element = (double) (java.lang.Math.random() * (max - 1));
arr.insert(element);
}
long endTime = System.currentTimeMillis();
System.out.println("Sort time: " + (endTime - startTime) + " ms");
}
}
class ArrayIns {
private double[] a;
private int nElement;
// --------------------------------------------------------
public ArrayIns(int max) {
a = new double[max];
nElement = 0;
}
// --------------------------------------------------------
public void insert(double element) {
a[nElement] = element;
nElement++;
}
// --------------------------------------------------------
public void display() {
for (int i = 0; i < nElement; i++)
System.out.print(a[i] + " ");
System.out.println();
}
// --------------------------------------------------------
public void insertionSort() {
int out, in;
for (out = 1; out < nElement; out++) {
double temp = a[out];
in = out;
while (in > 0 && a[in - 1] >= temp) {
a[in] = a[in - 1];
in--;
}
a[in] = temp;
}
}
}