import java.util.Arrays;
import java.util.Random;
import java.util.UUID;
public class StringSortTest3 {
static int limit = 8;
static Random random = new Random();
/**
* @param args
*/
public static void main(String[] args) {
int length = 1 * 100000;
String[] A = getStrs(length);
for (int j = 1; j < 50; j++) {
limit = j;
long l1 = System.currentTimeMillis();
int ci = 10;
for (int i = 0; i < ci; i++) {
int[] B = getIdx(length);
kuaiSu(A, B, length);
}
long l2 = System.currentTimeMillis();
System.out.println("-----------------limit = " + limit + " ------:" + (l2 - l1));
}
}
public static void verify(String[] strs, int[] idxs) {
String[] cs = new String[strs.length];
for (int i = 0; i < idxs.length; i++) {
cs[i] = strs[idxs[i]];
}
Arrays.sort(strs);
boolean flag = true;
for (int i = 0; i < idxs.length; i++) {
String str = strs[i];
String c = cs[i];
if(!str.equals(c)) {
flag = false;
break;
}
}
System.out.println("------------------" + flag + "------------------");
}
public static String[] getStrs(int length) {
String[] strs = new String[length];
for (int i = 0; i < length; i++) {
String id = UUID.randomUUID().toString();
strs[i] = id;
}
return strs;
}
public static int[] getIdx(int length) {
int[] idxs = new int[length];
for (int i = 0; i < length; i++) {
idxs[i] = i;
}
return idxs;
}
public static int[] getHL(int length) {
int[] idxs = new int[length];
for (int i = 0; i < length; i++) {
idxs[i] = -1;
}
return idxs;
}
// 快速排序(选定某个值分大小两个组,分别排序)
public static int[] kuaiSu(String[] A, int[] idxs, int n) {
if(n == 2) {
if(A[idxs[1]].compareTo(A[idxs[0]]) < 0) {
swap(idxs, 0, 1);
}
}
else if(n < limit) {
// 当长度小于limit时,用插入排序
chaRu(A, idxs, n);
}
else {
// 长度超过limit时,用快速排序
// 1.先分组
String key = A[idxs[random.nextInt(n)]];
int[] left = new int[n];
int[] right = new int[n];
int[] middle = new int[n];
int l = 0, r = 0, m = 0;
for (int i = 0; i < n; i++) {
int idx = idxs[i];
String temp = A[idx];
int comp = temp.compareTo(key);
if(comp < 0) {
left[l] = idx;
l++;
}
else if(comp == 0) {
middle[m] = idx;
m++;
}
else if(comp > 0) {
right[r] = idx;
r++;
}
}
// 2.分别排序
if(l > 1) {
left = kuaiSu(A, left, l);
}
if(r > 1) {
right = kuaiSu(A, right, r);
}
if(l > 0) {
System.arraycopy(left, 0, idxs, 0, l);
}
if(m > 0) {
System.arraycopy(middle, 0, idxs, l, m);
}
if(r > 0) {
System.arraycopy(right, 0, idxs, l + m, r);
}
}
return idxs;
}
// 插入排序
public static int[] chaRu(String[] A, int[] idxs, int n) {
//从数组的第二个元素开始循环将数组中的元素插入
for (int i = 1; i < n; i++) {
int tar = idxs[i];
int j = i-1;
while(j >= 0 && A[tar].compareTo(A[idxs[j]]) < 0) {
//如果要播讲的元素小于第j个元素,就将第j个元素向后移动
idxs[j+1] = idxs[j];
j--;
}
//直到要插入的元素不小于第j个元素,将insertNote插入到数组中
idxs[j+1] = tar;
}
return idxs;
}
public static void swap(int[] idxs, int i, int j) {
int temp = idxs[i];
idxs[i] = idxs[j];
idxs[j] = temp;
}