1. 程式人生 > >折半、快排、插入排序的Java實現

折半、快排、插入排序的Java實現

插入排序

  

import java.util.Arrays;

public class InsertionSort {

    /**
     * 對數組裡面進行插入排序
     * 引數1 陣列
     * 引數2 陣列大小
     */
    static void InsertSort(int arr[]){

        int in,out,temp;
        for ( out = 1; out < arr.length; out++) {
            temp = arr[out];
            in=out;
            
while (in>0 && arr[in-1]>=temp){ arr[in]=arr[in-1]; in--; } arr[in]=temp; } } public static void main(String[] args) { int[] arr={2,4,5,6,8,0,1,5,9,7}; InsertSort(arr); System.out.println(Arrays.toString(arr)); } }

快速排序

  

import java.util.Arrays;

public class QuickSort {

    /**
     * 快排
     * @param arr 用於排序的陣列
     * @param l 陣列的左邊界
     * @param r 陣列的右邊界
     */
    static void Quicktion(int arr[],int l,int r){

        int i,j,pivot;
        if(l<r){
            i=l;j=r;
            pivot=arr[i];
            
while (i<j){ while (i<j && arr[j]>pivot) j--;//從右往左 if(i<j){ arr[i]=arr[j]; i++; } while (i<j && arr[i]<pivot) i++;//從左往右 if(i<j){ arr[j]=arr[i]; j--; } } arr[i]=pivot; Quicktion(arr,l,i-1); Quicktion(arr,i+1,r); } } public static void main(String[] args) { int arr[] = {8,6,4,2,0,7,3,5,9}; Quicktion(arr,0,8); System.out.println(Arrays.toString(arr)); } }

折半查詢

public class BinSearch {

    /*遞迴版*/
    public static int binsearch1(int v[],int x,int left,int right){

        int middle;
        if(left<=right){
            middle=(left+right)/2;
            if(v[middle]==x) return middle;
            else if(a[middle]<x) left=middle+1;
            else if(a[middle]>x) right=middle-1;
            return binsearch1(v, x, left, right);
        }

    }

    /*迭代版*/
    public static int binsearch(int x,int v[],int n){

        int low,high,mid;
        low=0;high=n-1;
        while (low<=high){
            mid = (low+high)/2;
            if(x<v[mid]){
                high=mid-1;
            }else if(x>v[mid]){
                low=mid+1;
            }else{
                return mid;
            }
        }
        return -1;
    }


    public static void main(String[] args) {

        int arr[] = {1,3,4,5,6,7,8,10};
        int result,num;
        num=10;
        result = binsearch(num,arr,8);
        if(result<0){
            System.out.println("not found");
        }else{
            System.out.println(result+" , found……");
        }
    }
}