# Sort rectangles in a grid based on a comparison of the center point of each

If I have a grid of rectangles and I move one of the rectangles, say above and to the left of another rectangle, how would I resort the rectangles?

Note the rectangles are in an array, so each rectangle has an index and a matching tag. All I really need to do is set the proper index based on the rectangles new center point position within the rectangle, as compared with the center point position of the other rectangles in the grid. Here is what I am doing now in pseudo code (works somewhat, but not accurate):

``````-(void)sortViews:myView {
int newIndex;
// myView is the view that was moved.
[viewsArray removeObject:myView];
[viewsArray enumerate:obj*view]{
if (myView.center.x > view.center.x) {
if (myView.center.y > view.center.y) {
newIndex = view.tag -1;
*stop = YES;
} else {
newIndex = view.tag +1;
*stop = YES;
}
} else if (myView.center.x < view.center.x) {
if (myView.center.y > view.center.y) {
newIndex = view.tag -1;
*stop = YES;
} else {
newIndex = view.tag +1;
*stop = YES;
}
}
}];
if (newIndex < 0) {
newIndex = 0;
} else if (newIndex > 5) {
newIndex = 5;
}
[viewsArray insertObject:myView atIndex:newIndex];
[self arrangeGrid];
}
``````
• To sort objects we need a compare function that tells us when one object is less than or greater than another. In C-style languages this is typically done with a function that returns one of <0 (or -1), 0, >0 (or +1). So how do you define your compare function? Sep 17, 2013 at 5:48
• It can get rather complicated the way you're thinking about it now. @andy256 is right here. The best approach is to modify the position of the rectangle, and then apply a sort to ensure it remains consistent (hint: bubble and insertion sorts are best when you have almost sorted data).
– Neil
Sep 17, 2013 at 13:21