Objective-C:11.Sort

This commit is contained in:
Scarlett Che 2018-12-12 19:41:47 +08:00
parent 6b50ac0265
commit 90afeee723
3 changed files with 111 additions and 0 deletions

1
.gitignore vendored
View File

@ -18,6 +18,7 @@
*.zip
*.tar.gz
*.rar
*.DS_Store
# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml
hs_err_pid*

24
object-c/11_Sort/Sort.h Normal file
View File

@ -0,0 +1,24 @@
//
// Sort.h
// test1231231
//
// Created by Scarlett Che on 2018/12/12.
// Copyright © 2018 Scarlett Che. All rights reserved.
//
#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
@interface Sort : NSObject
// 冒泡排序
+ (NSArray *)bubbleSortWithArray:(NSArray *)array;
// 插入排序
+ (NSArray *)insertionSortWithArray:(NSArray *)array;
// 选择排序
+ (NSArray *)selectionSortWithArray:(NSArray *)array;
@end
NS_ASSUME_NONNULL_END

86
object-c/11_Sort/Sort.m Normal file
View File

@ -0,0 +1,86 @@
//
// Sort.m
// test1231231
//
// Created by Scarlett Che on 2018/12/12.
// Copyright © 2018 Scarlett Che. All rights reserved.
//
#import "Sort.h"
@implementation Sort
//
+ (NSArray *)bubbleSortWithArray:(NSArray *)array {
if (array.count <= 1) {
return array;
}
NSMutableArray *aryM = array.mutableCopy;
for (int i = 0; i < aryM.count - 1; i++) {
BOOL flag = NO; //
for (int j = 0; j < aryM.count - i - 1; j++) {
NSInteger value1 = [aryM[j] integerValue];
NSInteger value2 = [aryM[j + 1] integerValue];
if (value1 > value2) {
flag = YES;
[aryM exchangeObjectAtIndex:j withObjectAtIndex:j+1];
}
}
if (flag == NO) {
//
break;
}
}
return aryM.copy;
}
//
+ (NSArray *)insertionSortWithArray:(NSArray *)array {
NSMutableArray *aryU = array.mutableCopy;
for (int i = 1; i < aryU.count; i++) {
NSInteger value = [aryU[i] integerValue];
for (int j = 0; j < i; j ++) {
NSInteger sortedValue = [aryU[j] integerValue];
if (value < sortedValue) {
id obj = aryU[i];
[aryU removeObjectAtIndex:i];
[aryU insertObject:obj atIndex:j];
break;
}
}
}
return aryU.copy;
}
//
+ (NSArray *)selectionSortWithArray:(NSArray *)array {
if (array.count <= 1) {
return array;
}
NSMutableArray *aryM = array.mutableCopy;
for (int i = 0; i < array.count - 1; i++) {
NSInteger minIndex = NSNotFound;
NSInteger minValue = NSNotFound;
for (int j = i + 1; j < array.count - 1; j++) {
NSInteger tmp = [array[j] integerValue];
if (tmp < minValue) {
minValue = tmp;
minIndex = j;
}
}
if (minIndex != NSNotFound && minValue != NSNotFound && minValue < [array[i] integerValue]) {
[aryM exchangeObjectAtIndex:minIndex withObjectAtIndex:i];
}
}
return array;
}
@end