开发者

How to keep an array sorted

开发者 https://www.devze.com 2023-01-18 16:57 出处:网络
I\'m refactoring a project that involves passing around a lot of arrays.Currently, each method that returns an array sorts it right before returning it.This isn\'t ideal for a couple reasons -- there\

I'm refactoring a project that involves passing around a lot of arrays. Currently, each method that returns an array sorts it right before returning it. This isn't ideal for a couple reasons -- there's lots of duplicated code, it's inefficient to sort an array two or three times, and it's too easy to writ开发者_StackOverflow中文版e a new function but to forget to sort the array before returning it.

I'm looking for a way to guarantee that the array always kept in alphabetical order. My current thought is to subclass NSMutableArray and/or NSArray to create an alphabetized array class. I would need to override all of the methods that create or modify the array to call super and then sort itself.

Does this sound reasonable, or is there a better approach?

EDIT: Since performance issues have been mentioned, I'll include the relevant information from my project. Speed is not an important concern. The whole process only takes a few seconds, and the tool is only used every so often. So simplicity and obvious correctness is more important.

Also, the use case for arrays is specific. When an array is returned, the caller always accesses every element in the array at least once.


A balanced binary tree is the standard and efficient way to keep items sorted. Almost any way to do random access with a plain array will be slow. A skip list is also efficient and you may be able to add the functionality to the array class.


Check out CHDataStructures. It's a framework that has a lot of self-sorting datastructures, like balanced binary trees and whatnot.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号