七大排序算法
测试用例
public static void main(String[] args) {
int[] arr = {3,5,4,3,2,6,7,2,1};
String str = Arrays.stream(
sort(Arrays.copyOf(arr, arr.length))
).mapToObj(i->i+"").collect(Collectors.joining());
Arrays.sort(arr);
System.out.println(
Arrays.stream(arr).mapToObj(i->i+"").collect(Collectors.joining()).equals(str)
);
}
选择排序
public static int[] sort(int []rows) {
if (rows == null || rows.length == 0) return rows;
int len = rows.length;
for (int i = 0; i < len - 1; i++) {
int min = i;
for (int j = i+1; j < len; j++) {
if (rows[min] > rows[j]) {
min = j;
}
}
int tmp = rows[i];
rows[i] = rows[min];
rows[min] = tmp;
}
return rows;
}
快速排序
public static int[] sort(int[] rows, int lo, int hi) {
if (lo >= hi) {
return rows;
}
int index = part(rows, lo, hi);
sort(rows, lo, index-1);
sort(rows, index+1, hi);
return rows;
}
private static int part(int[] rows, int lo, int hi) {
//固定分隔
int key = rows[lo];
while (lo < hi){
while (rows[hi] >= key && hi > lo) {
hi--;
}
rows[lo] = rows[hi];
while (rows[lo] <= key && hi > lo) {
lo++;
}
rows[hi] = rows[lo];
}
rows[hi] = key;
return hi;
}
冒泡排序
public static int[] sort(int []rows) {
for (int i = 0; i < rows.length - 1; i++) {
for (int j = 0; j < rows.length - i - 1; j++) {
if (rows[j] > rows[j+1]) {
rows[j] = rows[j] ^ rows[j+1];
rows[j + 1] = rows[j] ^ rows[j+1];
rows[j] = rows[j] ^ rows[j+1];
}
}
}
return rows;
}
插入排序
public static int[] sort(int []rows) {
for (int i = 1; i < rows.length; i++) {
for (int j = i; j > 0 ; j--) {
if (rows[j] < rows[j-1]) {
rows[j] = rows[j] ^ rows[j-1];
rows[j - 1] = rows[j] ^ rows[j-1];
rows[j] = rows[j] ^ rows[j-1];
}
}
}
return rows;
}