1,给一个数组,用排序算法排序。 我写的是快排有点儿紧张就写乱了,回来重写一遍希望后面的人更加淡定。 public class QuickSort { public static String[] strings = new String[]{"a", "f", "n", "k", "l", "b"};
public static void main(String[] args) {
quickSort(strings, 0, strings.length - 1);
System.out.println(strings.toString());
}
private static int getPartition(String[] str, int low, int high) {
String partition = str[low];
while (low < high) {
while (low < high && str[high].compareTo(partition) >= 0) high--;
if (low < high) {
str[low] = str[high];
}
while (low < high && str[low].compareTo(partition) <= 0) low++;
if (low < high) {
str[high] = str[low];
}
}
str[low] = partition;
return low;
}
private static void quickSort(String[] strings, int low, int high) {
int base;
if (low < high) {
base = getPartition(strings, low, high);
quickSort(strings, low, base - 1);
quickSort(strings, base + 1, high);
}
}
}
2,数组的排序算法。 java环境给定一个数组排序是通过Collections.sort实现的。Collections.sort里面的排序算法是归并排序。
-
从下往上的归并排序:将待排序的数列分成若干个长度为1的子数列,然后将这些数列两两合并;得到若干个长度为2的有序数列,再将这些数列两两合并;得到若干个长度为4的有序数列,再将它们两两合并;直接合并成一个数列为止。这样就得到了我们想要的排序结果。(参考下面的图片)
-
从上往下的归并排序:它与"从下往上"在排序上是反方向的。它基本包括3步: ① 分解 -- 将当前区间一分为二,即求分裂点 mid = (low + high)/2; ② 求解 -- 递归地对两个子区间a[low…mid] 和 a[mid+1…high]进行归并排序。递归的终结条件是子区间长度为1。 ③ 合并 -- 将已排序的两个子区间a[low…mid]和 a[mid+1…high]归并为一个有序的区间a[low…high]。
private static void mergeSort(Object[] src,
Object[] dest,
int low,
int high,
int off) {
int length = high - low;
// Insertion sort on smallest arrays
if (length < INSERTIONSORT_THRESHOLD) {
for (int i=low; i<high; i++)
for (int j=i; j>low &&
((Comparable) dest[j-1]).compareTo(dest[j])>0; j--)
swap(dest, j, j-1);
return;
}
// Recursively sort halves of dest into src
int destLow = low;
int destHigh = high;
low += off;
high += off;
int mid = (low + high) >>> 1;
mergeSort(dest, src, low, mid, -off);
mergeSort(dest, src, mid, high, -off);
// If list is already sorted, just copy from src to dest. This is an
// optimization that results in faster sorts for nearly ordered lists.
if (((Comparable)src[mid-1]).compareTo(src[mid]) <= 0) {
System.arraycopy(src, low, dest, destLow, length);
return;
}
// Merge sorted halves (now in src) into dest
for(int i = destLow, p = low, q = mid; i < destHigh; i++) {
if (q >= high || p < mid && ((Comparable)src[p]).compareTo(src[q])<=0)
dest[i] = src[p++];
else
dest[i] = src[q++];
}
} -
排序算法分稳定排序和不稳定排序,每一个的适用场景是哪种? 快速排序(快),希尔排序(些),选择排序(选),堆排序(一堆)不是稳定的排序算法,而冒泡排序、插入排序、归并排序和基数排序是稳定的排序算法。适用场景真的是哎,孤陋寡闻。
-
项目架构和项目遇到的问题。 我最疑惑的是如果问dubbo不应该问容错机制和负载均衡么?可是面试官问如果服务依赖的dubbo挂了,该怎么继续运行该服务。哪位高手告诉我一下,跪求答案。我的理解是如果依赖的dubbo挂了要么就不让项目起来,要么就mock降级。谁告诉我还要咋样啊? 挂在一面,再见~