Java冒泡法和二分法

最近去一家公司面试,手贱在人家CTO面前自告奋勇写了一把冒泡法,结果在交换数据的时候出了洋相,回家反思,写下如下代码,对自己算是一个鞭策,得到的教训是不要眼高手低,低调前行。

 package com.defymedia.interview.sort;

 import java.util.ArrayList;
import java.util.List;
import java.util.Random; public class SimpleSort { public static final int NO_MATCH = -1; public <T extends Comparable> List<T> sort(List<T> list) {
int size = list != null ? list.size() : 0;
if (size == 0) return null; for (int i = 0; i < size; i++) {
for (int j = i + 1; j < size; j++) {
if (list.get(i).compareTo(list.get(j)) > 0) {
T temp = list.get(i);
list.set(i, list.get(j));
list.set(j, temp);
}
}
} return list;
} public <T extends Comparable> T[] sort(T[] ts) {
int size = ts != null ? ts.length : 0;
if (size == 0) return null; for (int i = 0; i < size; i++) {
for (int j = i + 1; j < size; j++) {
if (ts[i].compareTo(ts[j]) > 0) {
T temp = ts[i];
ts[i] = ts[j];
ts[j] = temp;
}
}
} return ts;
} public <T extends Comparable> int binarySearch(T[] ts, T t) {
int length = ts != null ? ts.length : NO_MATCH;
if (length <= 0 || t == null) return NO_MATCH; int middle;
int index = NO_MATCH;
int low = 0;
int high = length;
while (low < high) {
middle = (low + high) >> 1;
T temp = ts[middle];
if (temp.compareTo(t) > 0) {
high = middle;
} else if (temp.compareTo(t) < 0) {
low = middle;
} else {
index = middle;
break;
}
} System.out.println("index is " + index);
return index;
} public static void main(String[] param) {
SimpleSort simpleSort = new SimpleSort();
int size = 10;
Random random = new Random();
List<Integer> list = new ArrayList<>(size);
for (int i = 0; i < size; i++) {
list.add(random.nextInt(20));
}
list = simpleSort.sort(list);
for (Comparable comparable : list) {
System.out.println(comparable.toString());
}
Integer[] data = new Integer[size];
for (int i = 0; i < size; i++) {
data[i] = random.nextInt(50);
}
data = simpleSort.sort(data);
for (Comparable comparable : data) {
System.out.println(comparable.toString());
}
int number = NO_MATCH;
simpleSort.binarySearch(data, number);
}
}
上一篇:Java基础 随笔整理


下一篇:JAVA 冒泡算法