JAVA 实现各种排序算法和复杂度分析1
来源:互联网 发布:电力行业数据挖掘 编辑:程序博客网 时间:2024/05/21 03:20
<script type="text/javascript">google_ad_client = "pub-8800625213955058";/* 336x280, 创建于 07-11-21 */google_ad_slot = "0989131976";google_ad_width = 336;google_ad_height = 280;//</script><script type="text/javascript"src="http://pagead2.googlesyndication.com/pagead/show_ads.js"></script>第一种:冒泡排序public static int[] bubbleSort(int[] a) {for (int i = 0; i < a.length; i ) {for (int j = 0; j < (a.length - i) - 1; j ) {if (a[j] > a[j 1]) {int temp = a[j];a[j] = a[j 1];a[j 1] = temp;}}}return a;}复杂度分析:冒泡排序是不稳定的排序算法,一共要比较((n-1) (n-2) ... 3 2 1)=n*(n-1)/2次,所以时间复杂度是O(n^2)。第二种:选择排序public static int[] selecitonSort(int[] a) {for (int i = 0; i < a.length; i ) {int max = a[0];int count = 0;int k = a.length - i - 1;for (int j = 0; j < a.length - i; j ) {if (max < a[j]) {max = a[j];count = j;}}a[count] = a[k];a[k] = max;}return a;}复杂度分析:选择排序是不稳定算法,最好的情况是最好情况是已经排好顺序,只要比较n*(n-1)/2次即可,最坏情况是逆序排好的,那么还要移动 O(n)次,由于是低阶故而不考虑不难得出选择排序的时间复杂度是 O(n^2)第三种:插入排序待续。。。