I am very new to the Objective-C language and I was asked a question in the interview that I was not able to answer.
I tried a lot of approaches and logic to no success. Here looking for an answer:
The question was:
- (NSArray *)reorderTheArraysAndMergeThemInDescendingOrder:(NSArray *)firstArray and:(NSArray *)secondArray
Both the provided arrays in the argument are already sorted in ascending order.
My task was to provide an array as the return variable which will have all the unique elements of both firstArray and the secondArray and will have them in theh descending order. I was not allowed to use the inbuilt sorting functionality of Objective-C (that was the way I have been doing it ever since I am in this field). My variables may only be primitives (the result will be an integer array of course.).
I am new to the whole programming scene altogether and a good answer here will be MUCH appreciated.
Shukaku
Since the provided arrays are sorted in ascending order, this question is pretty-much related to the classic algorithm of
Mergesort(have a look at it if you’ve never heard of it, this is a classic).Since you’re array contain only primitive data types, they can be compared using
<The code that interest you would look like
I am not sure as to whether you want to remove duplicates, your question is not that clear, would you mind telling me if so so that i can improve my code ?
Edit : Did it anyway : since you’re array is sorted, duplicates are just next to each other, so it might be easy not to add them in the first place;
Edit : There are some errors in that code, because
icould become negative and afterward be used inobjectAtIndex:, this is just meant to demonstrate the idea, not to give an out-of-the-box code solution