快速排序
快速排序采用了二分的思想。
代码:
public class Sort {
// 全局变量
private int arr[];
// 快速排序方法,快速排序使用递归思想实现
public int[] quick(int[] arr) {
int l = arr.length;
this.arr = new int[l];
System.arraycopy(arr, 0, this.arr, 0, l); // 拷贝数组
sortLoop(0, l - 1);
return this.arr;
}
// 递归排序
private void sortLoop(int left, int right) {
int i, j, t, temp;
if (left > right) {
return;
}
temp = arr[left];
i = left;
j = right;
while (i != j) {
// 先从右往左找
while (arr[j] >= temp && i < j)
j--;
// 在从左往右找
while (arr[i] <= temp && i < j)
i++;
if (i < j) {
t = arr[i];
arr[i] = arr[j];
arr[j] = t;
}
}
// 最终将基数归位
arr[left] = arr[i];
arr[i] = temp;
sortLoop(left, i - 1);
sortLoop(i + 1, right);
}
}
测试:
public class SortTest {
private long startTime;
private Logger log = LoggerFactory.getLogger(SortTest.class);
private Sort sort = new Sort();
@Test
public void test() {
int[] quick = sort.quick(new int[] {3, 2, 5, 5, 1,3, 10, 7});
log.info("{}", quick);
}
@Before
public void before() {
startTime = System.currentTimeMillis();
}
@After
public void after() {
long timeConsuming = System.currentTimeMillis() - startTime;
log.info("快速排序耗时:{} ms", timeConsuming);
}
}
结果:
09:27:32.267 [main] INFO com.tang.SortTest - [1, 2, 3, 3, 5, 5, 7, 10]
09:27:32.267 [main] INFO com.tang.SortTest - 快速排序耗时:0 ms