Get the App
SLTechnology News&Howtos  ›  Development  › 

How to merge two ordered arrays with iOS algorithms

Shulou Source: shulou.com Published: 2022-06-03 06:14:13 09月24日 Update

How to use iOS common algorithms to merge two ordered arrays, I believe that many inexperienced people do not know what to do. Therefore, this paper summarizes the causes and solutions of the problem. Through this article, I hope you can solve this problem.

Train of thought:

General ideas:

First take an array as the merged array, then iterate through each element of the second array, compare it one by one, and insert it until you find a suitable one.

Simple idea: set array C, compare the first element of array An and B, find the smallest, put it into array C, and proceed in turn.

The code is as follows:

-(NSArray *) mergeOrderArrayWithFirstArray: (NSMutableArray *) array1 secondArray: (NSMutableArray *) array2 {/ / all empty do not handle if (! array1.count & &! array2.count) {return @ [];} / / one returns another if (! array1.count) {return array2;} if (! array2.count) {return array1;} NSMutableArray * endArray = [NSMutableArray array] While (1) {if ([array1 [0] integerValue] < [array2 [0] integerValue]) {[endArray addObject:array1 [0]]; [array1 removeObjectAtIndex:0];} else {[endArray addObject:array2 [0]]; [array2 removeObjectAtIndex:0];} if (! array1.count) {[endArray addObjectsFromArray:array2]; break;} if (! array2.count) {[endArray addObjectsFromArray:array1]; break;}} return endArray;}

After reading the above, have you mastered how to merge two ordered arrays using the common algorithms of iOS? If you want to learn more skills or want to know more about it, you are welcome to follow the industry information channel, thank you for reading!

Tags: Array idea order two commonly used algorithm combination element content method more problem fit minimum helpless for this number code reason for this Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno vpn Shulou Information Microsoft MySQL OPPO Reno