合并算法

//

//  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


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值