别再问我选择排序时间复杂度为什么是n^2了
今天同事问了我一个问题,选择排序的时间复杂度为啥是n^2。(真无语,我一个写业务的,突然问我这个问题,有病呀),然后我就给他解释了一番,但是他说他听不懂,我就重新详细的讲了一遍,他还说他听不懂,我直接。。。。,就写了这个,我就很杠,这t喵的不应该是个大学毕业的都看的懂吗!!!
我给他写的代码
第一遍:我语气温和的说:“诺,选择排序就这样呀”
public class SelectSort {
public static void sort(int[] arr) {
if (arr == null || arr.length < 2) {
return;
}
for (int i = 0; i < arr.length - 1; i++) {
int minIndex = i;
for (int j = i + 1; j < arr.length; j++) {
if (arr[j] < arr[i]) {
minIndex = j;
}
}
if (minIndex != i) {
int temp = arr[i];
arr[i] = arr[minIndex];
arr[minIndex] = temp;
}
}
}
public static void main(String[] args) {
int[] arr = new int[]{1, 2, 4, 3, 1};
Arrays.stream(arr).forEach(a -> System.out.print(a + " "));
System.out.println();
sort(arr);
Arrays.stream(arr).forEach(a -> System.out.print(a + " "));
System.out.println();
}
}
同事:这两个for循环,内部又不是遍历n次,外部也就n-1次,怎么时间复杂度就是n^2呢?
我:emmm,我看了下代码,也没注释,我又看了看他,他好像没耍我,我就耐心的给他解释了一遍
选择排序 时间复杂度 o(n^2)
计算方式:
= (n-1) + (n -2) + (n -3) + ... + 1
= n * (n-1)/2
= n^2/2 - n/2
时间复杂度 - 去除常数并只需要最高次幂
去除常数: n^2 -n
只要最高次幂: n^2
同事:时间复杂度是这样算的吗,我还是没太明白
我:。。。。 。。。。 。。。。 这就是这样呀(我看了看他,我没说话了,在公司,没有隔着网络,不好发作)
本人就记录下,用个标题表达下我的心境(我是不是该换个公司了,这是真水还是装的呀,🌚)。