学习快速排序和二分查找算法

       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)小,效率高。
 

posted on 2016-10-15 17:23  xjz1842  阅读(3704)  评论(0编辑  收藏  举报

导航