二分查找、冒泡排序举例

二分查找也称折半查找(Binary Search),它是一种效率较高的查找方法。但是,折半查找要求线性表必须采用顺序存储结构,而且表中元素按关键字有序排列。

package org.bc.offer.algorithm;

import org.bc.offer.thread.NewThread;

public class BinarySearch
{
    public static int binarySearch(int []array,int a){
        int low=0;
        int high=array.length-1;
        int mid;
        while(low<=high){
            mid=low+(high-low)/2;
            if(a==array[mid]){
                return mid;
            }else if(a>array[mid]){
                low=mid+1;
            } else{
                high=mid-1;
            }
        }
        return -1;
    }

    public static void main(String[] args) throws Exception {
    int data[]={0,2,4,6,7,8};
    System.out.println(binarySearch(data,0));
        System.out.println(binarySearch(data,4));
        System.out.println(binarySearch(data,7));
        System.out.println(binarySearch(data,8));


    }
}

0
2
4
5

Process finished with exit code 0

冒泡排序(Bubble Sort),是一种计算机科学领域的较简单的排序算法。
它重复地走访过要排序的元素列,依次比较两个相邻的元素,如果顺序(如从大到小、首字母从Z到A)错误就把他们交换过来。走访元素的工作是重复地进行,直到没有相邻元素需要交换,也就是说该元素列已经排序完成。
这个算法的名字由来是因为越小的元素会经由交换慢慢“浮”到数列的顶端(升序或降序排列),就如同碳酸饮料中二氧化碳的气泡最终会上浮到顶端一样,故名“冒泡排序”。

package org.bc.offer.algorithm;

public class BubbleSort {
    public static int[] bubbleSort(int [] array){
        for(int i=0;i array[j+ 1]) {
                    int temp =array[j];
                    array[j]=array[j+ 1];
                    array[j+ 1]=temp;
                }
            }
        }
        return array;
    }

    public static void main(String[] args) throws Exception {
        int data[]={4,5,6,3,2,1};

        bubbleSort(data);
        System.out.println("");
        for(int i=0;i
1 2 3 4 5 6 

Process finished with exit code 0

你可能感兴趣的:(数据结构举例,java,算法,数据结构)