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