forked from gl-lei/algorithm
- Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathMergeTwoSortedArray.swift
More file actions
Latest commit
64 lines (58 loc) · 1.66 KB
/
Copy pathMergeTwoSortedArray.swift
File metadata and controls
64 lines (58 loc) · 1.66 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
//
// MergeTwoSortedArray.swift
// Array
//
// Created by ggl on 2019/3/21.
// Copyright © 2019年 ggl. All rights reserved.
//
import Foundation
/// 合并两个有序数组为一个有序数组
///
/// - Parameters:
/// - arrOne: 第一个有序数组
/// - arrOneCount: 第一个有序数组的大小
/// - arrTwo: 第二个有序数组
/// - arrTwoCount: 第二个有序数组的大小
/// - Returns: 新的有序数组(需要释放)
func mergeTwoSortedArray(arrOne:UnsafePointer<Int>, arrOneCount:Int, arrTwo:UnsafePointer<Int>, arrTwoCount:Int)->UnsafePointer<Int>{
letnewArray= UnsafeMutablePointer<Int>.allocate(capacity: arrOneCount + arrTwoCount)
vari=0,j=0
forindexin0..<(arrOneCount + arrTwoCount){
//判断i和j有没有到头
if i > arrOneCount-1{
newArray[index]=arrTwo[j]
j +=1
}elseif j > arrTwoCount-1{
newArray[index]=arrOne[i]
i +=1
}else{
letnum1=arrOne[i]
letnum2=arrTwo[j]
if num1 > num2 {
newArray[index]= num2
j +=1
}else{
newArray[index]= num1
i +=1
}
}
}
returnUnsafePointer(newArray)
}
/// 打印数组内容
///
/// - Parameter arr: 数组
func printArray(arr:UnsafePointer<Int>, count:Int){
if count ==0{
print("[]")
return
}
print("[", terminator:"")
foriin0..<count {
if i == count -1{
print(arr[count-1], terminator:"]\n")
}else{
print(arr[i], terminator:"")
}
}
}