学习快速排序和二分查找算法
2016-10-15 17:23
127 查看
1. 快速排序的思想采用的是分治算法实现,从头选择一个元素是作为“哨兵元素”,然后从尾部开始寻找一个比“哨兵元素“小的元素,然后跟它交换,接着从头开始寻找比“哨兵元素“大的;元素,然后交换,直到“哨兵元素“的左边都“哨兵元素“小,右边都比“哨兵元素“大为止,这算是一次划分,快速排序是要经过的 k-1趟(假设有k个元素)划分才能排序好所有的元素。 下面根据分治实现的java代码:
public class QuickSort { public static void main(String[] args) { Integer[] a = new Integer[]{1,4,775,34,22,67}; for(Integer e : a){ System.out.print(e + " "); } System.out.println(); quickSort(a,0,a.length-1); for(Integer e : a){ System.out.print(e + " "); } } public static int getMiddle(Integer[] a, int low, int high){ int key = a[low]; while(low < high){ //从最高开始寻找一个比key小的元素,然后交换 while(low < high && a[high] > key){ high--; } a[low] = a[high]; //从头开始查找一个比key大的元素,然后交换 while (low < high && a[low] < key){ low++; } a[high] = a[low]; } //将正确的位置放在正确的位置 a[low] = key; return low; } public static void quickSort(Integer a[], int low, int high){ if(low > high)return; if(low < high){ int middle = getMiddle(a,low,high); quickSort(a,low,middle-1); quickSort(a,middle+1,high); } }
算法的性能是O(NogN),快速排序的最差的性能是O(n*n),最差性能是在每次的划分选取的"哨兵元素"都是改划分的最小元素。那么这样它每次划分都是只有一个段,失去了快速排序多次划分的优势,复杂度又退回n的平方。
2.二分查找的比较简单的算法,它默认是有序数组,它是每次选取数组的元素的中间索引值比较,如果比目标值大,则目标值可能在数组的中间的位置到数组的末尾的位置,然后接着比较
数组的中间的位置到数组的末尾的位置的中间位置的值和目标值比较,直到找到最小的索引(low) 大于最大的索引(high)为止。 下面是实现的java代码:
package com.algorithm.sort; public class BinarySerach { private static final int t = 4; public static void main(String[] args) { Integer[] a = new Integer[]{1,4,775,34,22,67}; int result = binarySearch(a,0,a.length-1); System.out.println(a[result]); } //默认数组是排序的 public static int binarySearch(Integer[] a,int left , int right){ while (left <= right){ int mid = (left +right)>>1; if(a[mid] > t){ right = mid - 1; }else if(a[mid] < t){ left = mid+1; }else{ return mid; } } return -1; } //分治算法 public int bsearch(int array[], int low, int high, int target) { if (low > high) return -1; int mid = (low + high)/2; if (array[mid]> target) return bsearch(array, low, mid - 1, target); if (array[mid]< target) return bsearch(array, mid+1, high, target); //if (midValue == target) return mid; } }
二分查找的算法复杂度O(logn),它比顺序查找的时间复杂度O(n)小,效率高。
相关文章推荐
- C++学习 - 快速排序,更加优化的实现
- 快速排序学习2(随机化版本)
- c++学习之--排序3-快速排序
- 快速排序学习
- 算法学习--希尔和快速排序
- 快速排序与二分查找算法Javascript版本
- 我的编程学习日志(8)--排序(冒泡,选择,快速以及sort函数)
- 算法导论 第7章 快速排序 学习总结
- 快速排序学习笔记
- c语言快速排序与二分查找算法
- 快速排序学习4(最初版加随机版)
- 交换排序:快速排序 学习
- 快速排序和二分查找算法的实现C语言
- mongodb中的排序和索引快速学习
- 算法导论学习笔记(五):快速排序
- 快速排序学习1
- 快速排序 php实现 算法学习
- 算法学习之排序学习之快速排序
- 快速排序学习
- 算法学习 - 归并排序,快速排序,冒泡排序