Several NSArray sorting:

Source: Internet
Author: User
Tags allkeys

Several NSArray sorting:

#Use the ArraySortedArrayUsingComparatorCall NSComparator

NSComparator is actually a block that returns NSComparisonResult.

Typedef NSComparisonResult (^ NSComparator) (id obj1, id obj2); where obj1 and obj2 are actually elements in NSArray

    resultArray = [arrayDic <span style="color:#009900;">sortedArrayUsingComparator:</span>^NSComparisonResult(id obj1, id obj2) {        NSNumber * number1 = [[obj1 allKeys] objectAtIndex:0];        NSNumber * number2 = [[obj2 allKeys] objectAtIndex:0];        NSComparisonResult result = [number1 compare:number2];        return result == NSOrderedAscending;    }];

#Use the sortedArrayUsingFunction of the array to call the corresponding method customSort

NSInteger <span style = "color: # ff9900;"> sortByID </span> (id obj1, id obj2, void * context) {NSString * str1 = (NSString *) obj1; // ibj1 and obj2 come from your array. In fact, I personally think Apple has implemented a bubble sort for you to use NSString * str2 = (NSString *) obj2; if (str1.length <str2.length) {<span style = "white-space: pre"> </span> return NSOrderedDescending;} else if (str1.length = str2.length) {<span style = "white-space: pre"> </span> return NSOrderedSame;} <span style = "white-space: pre "> </span> return NSOrderedAscending ;}
NSArray *sortedArray =[arr sortedArrayUsingFunction:sortByID context:nil];

# Using arraySortedArrayUsingSelector calls the corresponding SEL Method

Note that the selector method is for array elements. If the data element does not have the compare method, you can add the corresponding method by extending the class of array elements.

    NSMutableArray *arrayDic = [NSMutableArray arrayWithObjects:                             [NSDictionary dictionaryWithObjectsAndKeys:@"Obj0", [NSNumber numberWithInt:0], nil],                             [NSDictionary dictionaryWithObjectsAndKeys:@"Obj5", [NSNumber numberWithInt:5], nil],                             [NSDictionary dictionaryWithObjectsAndKeys:@"Obj2", [NSNumber numberWithInt:2], nil],                             [NSDictionary dictionaryWithObjectsAndKeys:@"Obj3", [NSNumber numberWithInt:3], nil],                             [NSDictionary dictionaryWithObjectsAndKeys:@"Obj1", [NSNumber numberWithInt:1], nil],                             [NSDictionary dictionaryWithObjectsAndKeys:@"Obj4", [NSNumber numberWithInt:4], nil], nil];#ifdef sortedArrayUsingSelector    resultArray = [arrayDic sortedArrayUsingSelector:@selector(compare:)];

Because the elements in the array correspond to dictionaries, the dictionary classes are extended.

@ Implementation Dictionary (extend)-(optional) compare: (NSDictionary *) otherDictionary {NSNumber * number2 = [[otherDictionary allKeys] objectAtIndex: 0]; NSDictionary * tempDictionary = (NSDictionary *) self; NSNumber * number1 = [[tempDictionary allKeys] objectAtIndex: 0]; NSComparisonResult result = [number1 compare: number2]; // return result = NSOrderedDescending; // return result = NSOrderedAscending in ascending order; // descending order}

# Using arraySortUsingDescriptors call NSSortDescriptor

NSSortDescriptor can be simply understood as a comparative description of an attribute of a specified object.

/*** It is convenient to sort by a certain attribute in the model object. * sortDescriptor1 array is sorted in ascending order by name * sortDescriptor2 array is sorted in descending order by age * two types of sortDescriptor add an array, sort by name first, and sort by age with the same name */Person * person1 = [[Person alloc] init]; [person1 setName: @ "ABC"]; [person1 setAge: 24]; Person * person2 = [[Person alloc] init]; [person2 setName: @ "ACB"]; [person2 setAge: 22]; person * person3 = [[Person alloc] init]; [person3 setName: @ "ABD"]; [person3 setAge: 33]; NSMutableArray * array = [NSMutableArray arrayWithObjects: person1, person2, person3, nil]; NSSortDescriptor * sortDescriptor1 = [NSSortDescriptor <span style = "color: # ff0000;"> sortDescriptorWithKey </span>: @ "_ name" ascending: YES]; NSSortDescriptor * sortDescriptor2 = [NSSortDescriptor <span style = "color: # ff0000;"> sortDescriptorWithKey </span>: @ "_ age" ascending: NO]; resultArray = [array sortedArrayUsingDescriptors: [NSArray arrayWithObjects: sortDescriptor1, sortDescriptor2, nil]; for (NSInteger I = 0; I <[resultArray count]; I +) {NSLog (@ "% @ -------- % d \ n", [[resultArray objectAtIndex: I] name], [[resultArray objectAtIndex: I] age]);}


Which of the following algorithms does C ++ use to sort arrays?

Insert Sorting Algorithm
1. From ordered series and unordered series {a2, a3 ,..., An} starts sorting;
2. When processing the I-th element (I = 2, 3 ,..., N), series {a1, a2 ,..., Ai-1} is already ordered, and the series {ai, ai + 1 ,..., An} is unordered. With ai and ai-1, a I-2 ,..., A1 comparison to find a suitable location for ai insertion;
3. Repeat Step 2 and perform n-1 insertion operations. The sequence is all ordered.
Void insertSort (Type * arr, long len)/* InsertSort algorithm */
{
Long I = 0, j = 0;/* iterator value */
Type tmpData;
AssertF (arr! = NULL, "In InsertSort sort, arr is NULL \ n ");
For (I = 1; I <len; I ++)
{
J = I;
TmpData = * (arr + I );
While (j> 0 & tmpData <arr [J-1])
{
Arr [j] = arr [J-1];
J --;
}
Arr [j] = tmpData;
}
}

Merge Sorting: Merge Sorting combines two or more ordered tables into a new ordered table multiple times. The simplest merge operation is to directly merge two ordered sub-tables into an ordered table.
# Include <stdio. h>
# Include <stdlib. h>
# Include <iostream. h>
Void merge (int array [], int p, int q, int r)
{
Int * temp = new int [r-p + 1]; // apply for a space, so that the size is the sum of the two sorted sequences. This space is used to store the merged sequence.
Int m = p;
Int n = q + 1;
Int k = 0;
While (m <= q) & (n <= r) // compare the elements pointed to by two subscripts, and select a relatively small element to put it into the merging space, move the subscript to the next position.
{
If (array [m] <array [n])
{
Temp [k] = array [m];
M ++;
}
Else
{
Temp [k] = array [n];
N ++;
}
K ++;
}
While (m <= q) // if the first sequence has surplus, copy it directly and paste it to the end of the merged Sequence
{
Temp [k] = array [m];
K ++;
M ++;
}
While (n <= r) // if the second sequence has surplus, copy it directly and paste it to the end of the merged Sequence
{
Temp [k] = array [n];
K ++;
N ++;
}
For (int I = 0; I <(r-p + 1); I ++) // copy the sorted sequence back to the array.
{
Array [p + I] = temp [I];
}
}
Void mergesort (int A [], int p, int r)
{
If (p <r)
{
Int q = (p + r)/2;
Mergesort (A, p, q );
Mergesort (A, q + 1, r );
Merge (A, p, q, r );
... The remaining full text>

Several common sorting algorithms

/*** @ Author txin0814 E-mail: txin0814@sina.com * @ version 1.0 * @ date Apr 1, 2011 2:28:06 PM * @ description base class of the sorting class */public abstract class BaseSorter {public abstract void sort (E [] array, int from, int len ); public final void sort (E [] array) {sort (array, 0, array. length);} protected final void swap (E [] array, int from, int to) {E temp = array [from]; array [from] = array [to]; array [to] = temp ;}}/** * @ Author txin0814 E-mail: txin0814@sina.com * @ version 1.0 * @ date Apr 1, 2011 2:34:47 * @ description insert sort this algorithm is very efficient when the data size is small, * This algorithm inserts a proper position from K + 1 to the first K ordered arrays each time, * K starts from 0 to N-1, to complete sorting */public class InsertSorter extends BaseSorter {// public static boolean SORT_TYPE = false in ascending order when SORT_TYPE is set to false in descending order; @ Override public void sort (E [] array, int from, int len) {E tmp = null; for (int I = from + 1; ifrom; j --) {If (SORT_TYPE) {if (tmp. compareTo (array [J-1]) 0) {array [j] = array [J-1];} else break;} array [j] = tmp ;} /* for (E: array) {System. out. println (e);} */} public static void main (String [] args) {Integer [] elem = {32, 43, 1, 3, 54, 4, 19}; InsertSorter insertsort = new InsertSorter (); // InsertSorter. SORT_TYPE = true; insertsort. sort (elem); for (Integer integer: elem) {System. out. println (intege R); }}/ *** @ author txin0814 E-mail: txin0814@sina.com * @ version 1.0 * @ date Apr 1, 2011 2:53:29 * @ description the Bubble sorting algorithm compares two adjacent elements from the end of the array each time, and bubbles the smallest I to the position I of the array .) */Public class BubbleSorter extends BaseSorter {// when SORT_TYPE is false, it is sorted in descending order as TR ...... the remaining full text>

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.