Sort numeric array

Discussion in 'Mac Programming' started by JonnyThunder, Sep 12, 2008.

  1. macrumors member


    Can anyone tell me how to sort an array. I have an array of number objects as per the code below and I'd like to sort them into numerical ascending order.

    #import <Foundation/Foundation.h>
    int main (int argc, const char * argv[]) {
        NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
    	// Set up some vars
    	int numbersPerLine = 6;
    	int maximumChoosableNumber = 49;
    	// Create a mutable array for holding all numbers in one line
    	NSMutableArray *line = [[NSMutableArray alloc] init];
    	// Seed the random number generator
    	// Cycle through number choices for a line
    	for (int i=0; i<numbersPerLine; i++)
    		// Set a flag for checking duplicates
    		BOOL checker = false;
    		while (!checker) {
    			// Make my random number
    			int randomnumber = ((random()%maximumChoosableNumber)+1);
    			// Make a number object and init with the random number
    			NSNumber *num = [[NSNumber alloc] initWithInt:randomnumber];
    			// Check the number doesn't exit in my 'already chosen' numbers
    			if ([line indexOfObject:num] == NSNotFound)
    				// Add the new number to the array
    				[line addObject:num];
    				checker = true;
    		NSLog(@"Number %d is %@", i, [line objectAtIndex:i]);
        [pool drain];
        return 0;
  2. macrumors regular

    Hi JonnyThunder,

    you can sort a NSMutableArray using the sortUsingDescriptors: , sortUsingFunction:context: and sortedArrayUsingSelector: methods.

    Here is a complete guide on CocoaDev about how to sort using selectors:
  3. Moderator


    Staff Member

    This is the sort of question that is often set as an assignment in a programming class or as homework: if this is either of those it is considered good form to say so (especially as it will alter the answer).

    Assuming this is not an assignment and you can use the built in API (for an assignment you would normally be expected to implement a sort algorithm yourself, but as you have made no attempt at that neither will I) I would read the documentation on sorting an NSArray.
  4. macrumors member

    Robbie: I HAD attempted sorting an array but didn't get it to work. I used AppKiDo to find the sortUsingSelector method for the class and tried to get it running, but failed. (Yes, that's right - some of us DO make mistakes while learning new things)

    I always read the documentation and try to implement. If it doesn't work, I post on forums. The idea (at least in my head anyway) is that people who post to forums actually want to help others. If you have no intent of doing anything other than trying to make me feel stupid (sadly there are people like that in the world) then please don't waste my time.

    Whats with you anyway? Didn't you once start by knowing nothing about Obj-C? By the way, I'm 33 years old and work as a Systems Administrator. Programming is a hobby, therefore your assumption (again) about homework is way off base.

    Mac Player: Thanks for that. Didn't know about that site - but looks quite useful!
  5. Moderator


    Staff Member

    As I said this is a very common homework/assignment question. Many people post this sort of question to these forums hoping that someone else will do their work for them. I was simply trying to ensure that was not the case.

    If you had attempted something do you not think it would be better to say so and show what you tried and explain why it failed? Simply posting what you did gives the impression that you have not tried anything or read the documentation. In that case I find the best thing to do is to point people at the correct part of the documentation so as they can learn themselves. This leads to a greater understanding of the API and normally a greater sense of satisfaction.

    So why not post the code that you tried to use and then perhaps we can point out any errors and you can get it working instead of expecting us to write if for you and then whining like a spoilt child when we don't.
  6. macrumors member

    You mean, like I did yesterday - when you so helpfully told me I should go back to the start of reading the Apple manual for ObjC, because of a typo?

    Anyway, Mac Players post helped me out a great deal. I learn better from written examples than I do from documentation (it's easier for me to visualise a solution if I can see how it fits together).

    The line I was looking for was :

    [line sortUsingSelector:@selector(compare:)];
  7. macrumors 68040


    you're being quite defensive. There was a conditional in regard to this being an assignment, not an accusation. Often posters here are new to cocoa, so links to the docs are helpful. You're asking for help, but when advice is offered in good faith you retaliate as if you were personally attacked. People here are trying to help. Just relax and I'm sure you'll get all the help you need.


Share This Page