您的位置:首页 > 移动开发 > IOS开发

合并算法

2015-12-08 16:07 363 查看
//

//  ViewContrller2.m

//  Sort

//

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

//  Copyright © 2015年 apple. All rights reserved.

//

#import "ViewContrller2.h"

#import "Header.h"

@implementation ViewContrller2

- (void)viewDidLoad {

    

    [super
viewDidLoad];

    

    self.view.backgroundColor = [UIColor
whiteColor];

    int arr[10] = {12,36,47,58,10,41,43,93,148,1200};

    

    //mergeOneArrTwoSection(arr, 0, 4, 9);

    mergeSort(arr,
0, 9);

    

    printCArr(arr,
10);

    

}

//合并一个数组里面的
两个部分

void mergeOneArrTwoSection(int * a,int left ,int mid,int right) {

    

    if (left < right) {

        

        

        int leftSectionCount = mid - left +
1; // 左边的个数

        int rightSectionCount= right - mid;//右边的个数

        

        int temp[100] = {0};
//用来缓存
左右分区的数据

        

        int leftIndex = left;
//左边的起始值

        int rightIndex= mid+1;//右边的起始值

        int tempIndex =
0;// 缓存的起始值

        

       
//同时布局左右分区的数组

        while (leftSectionCount>0 && rightSectionCount >0) {

            

            if (a[leftIndex] < a[rightIndex]) {

                temp[tempIndex++] = a[leftIndex++];

                leftSectionCount--;

            }else {

                temp[tempIndex++] = a[rightIndex++];

                rightSectionCount -- ;

            }

            

        }

        

       
// 如果走了这个说明
只剩下左边分区

        while (leftSectionCount >0) {

            

            temp[tempIndex++] = a[leftIndex++];

            leftSectionCount--;

        }

        

       
// 如果走了这个说明
只剩下右边分区

        while (rightSectionCount >0) {

            

            temp[tempIndex++] = a[rightIndex++];

            rightSectionCount--;

        }

        

        //从新把temp
值赋值给a

        int i = 0;

        while (left+i <= right) {

            a[left+i] = temp[i];

            i++;

        }

        

        

    }

    

    

}

void mergeSort(int * a,int left ,int right) {

    

    if (left < right) {

        

        int mid = (left + right)/2;

        mergeSort(a, left, mid);
// 左边有序

        mergeSort(a, mid+1, right);//
右边有序

        mergeOneArrTwoSection(a, left, mid, right);//
合并

    }

    

}

@end
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  ios 分治 合并