二叉搜索 方法

来源:互联网 发布:网络流行欧美歌曲 编辑:程序博客网 时间:2024/06/02 02:01

//

//  ViewController3.m

//  Sort

//

//  Created by apple on 15/12/12.

//  Copyright © 2015 apple. All rights reserved.

//


#import "ViewController3.h"


@interface ViewController3 ()


@end


@implementation ViewController3


- (void)viewDidLoad {

    [superviewDidLoad];

    // Do any additional setup after loading the view. 


    // 二叉搜索的 是对一个有序的数组进行搜索 它的时间复杂度是 O(logn) 好于顺序的 O(n)

    int arr[10] = {12,36,47,58,160,241,343,493,548,612};

    int find = binarySearch(arr,0, 9,241);

    

    printf("find = %d",find);

    

}



int binarySearch(int * a,int left,int right,int num) {

    

    

    if (left <= right) {

        

        int leftTemp = left;

        int rightTemp= right;

        

        int binaryIndex = (left+right)/2;

        int numTemp = a[binaryIndex];

        

        if (numTemp > num ) {

            rightTemp = binaryIndex - 1;

        }else if(numTemp < num) {

            leftTemp =  binaryIndex + 1;

        }else {

            return 1;

        }

        

        binarySearch(a, leftTemp, rightTemp,num);

        

    }

    return -1;

}



@end


0 0