1、二分法查找
當(dāng)數(shù)據(jù)量很大適宜采用該方法。采用二分法查找時(shí),數(shù)據(jù)需是有序的,否則要先排序。
- (void)binarySearchWithArray:(NSArray *)array searchNum:(NSInteger)searchNum
{
? ? NSArray *arr = [NSArray arrayWithArray:array];
? ? NSInteger mid;
? ? NSInteger min = 0;
? ? NSInteger max = [arr count] - 1;
? ? BOOL found = NO;
? ? while (min<=max) {
? ? ? ? mid = (min + max)/2;
? ? ? ? if (searchNum == [arr[mid] intValue]) {
? ? ? ? ? ? NSLog(@"我們發(fā)現(xiàn)數(shù)量!它是======》%@",arr[mid]);
? ? ? ? ? ? found = YES;
? ? ? ? ? ? break;
? ? ? ? }
? ? ? ? else if(searchNum < [arr[mid] intValue]) {
? ? ? ? ? ? max = mid - 1;
? ? ? ? }
? ? ? ? else if (searchNum > [arr[mid] integerValue]) {
? ? ? ? ? ? min = mid + 1;
? ? ? ? }
? ? }
? ? if (!found) {
? ? ? ? NSLog(@"這個(gè)數(shù)字沒有找到.");
? ? }
}
2、冒泡排序
冒泡排序會(huì)重復(fù)地走訪過要排序的數(shù)列,一次比較兩個(gè)元素,如果他們的順序錯(cuò)誤就把他們交換過來。走訪數(shù)列的工作是重復(fù)地進(jìn)行直到?jīng)]有再需要交換,也就是說該數(shù)列已經(jīng)排序完成。
- (void)bubbleSortWithArray:(NSArray *)array{ NSMutableArray *arr = [NSMutableArray arrayWithArray:array]; for (int i = 0; i<[arr count]; ++i) { for (int j = 0; j<[array count] - i - 1; ++j) { NSInteger left = [arr[j] integerValue]; NSInteger right = [arr[j+1] integerValue]; if (left %@",arr);
}