冒泡排序的实现
/**
冒泡排序实现
@param dataArray 需要排序的数组
@return 排序完成的数组
*/
- (NSArray *)buddleSort:(NSArray <NSNumber *> *)dataArray{
NSMutableArray <NSNumber *> * resultArray = [NSMutableArray arrayWithArray:dataArray];
for (int i = 0; i < [dataArray count] - 1; i ++) {
for (int j = 0; j < [dataArray count] - 1 - i; j ++) {
if (resultArray[j].integerValue > resultArray[j + 1].integerValue) {
[resultArray exchangeObjectAtIndex:j withObjectAtIndex:j + 1];
}
}
}
return resultArray;
}
快速排序的实现
/**
快速排序
@param dataArray 需要排序的数组
@param leftIndex 左边的index
@param rightIndex 右边的index
*/
- (void)quickSort:(NSMutableArray *)dataArray leftIndex:(NSInteger)leftIndex rightIndex:(NSInteger)rightIndex{
if (leftIndex >= rightIndex) {
return;
}
NSInteger i = leftIndex;
NSInteger j = rightIndex;
NSInteger key = [dataArray[i] integerValue];
while (i != j) {
//先从右边找
while (i < j && [dataArray[j] integerValue] >= key) {
j --;
}
//再从左边找
while (i < j && [dataArray[i] integerValue] <= key) {
i ++;
}
if (i < j) {
[dataArray exchangeObjectAtIndex:i withObjectAtIndex:j];
}
}
[dataArray exchangeObjectAtIndex:leftIndex withObjectAtIndex:j];
//递归剩下的左边和右边
[self quickSort:dataArray leftIndex:leftIndex rightIndex:i - 1];
[self quickSort:dataArray leftIndex:i + 1 rightIndex:rightIndex];
}
两个有序数组合并成一个有序数组的实现(插入排序)
/**
两个有序数组合并
@param firstArray 第一个数组
@param secondArray 第二个数组
@return 合并的数组
*/
- (NSArray *)insertSort:(NSArray *)firstArray secondArray:(NSArray *)secondArray{
NSMutableArray * resuleArray = [NSMutableArray arrayWithCapacity:[firstArray count] + [secondArray count]];
NSInteger i = 0;
NSInteger j = 0;
while (i < [firstArray count] && j < [secondArray count] ) {
if (firstArray[i] <= secondArray[j]) {
resuleArray[i + j] = firstArray[i ++];
}else{
resuleArray[i + j] = secondArray[j ++];
}
}
//保证数组剩余的部分加入合并后的数组中
while (i < [firstArray count]) {
resuleArray[i + j] = firstArray[i ++];
}
while (j < [secondArray count]) {
resuleArray[i + j] = secondArray[j ++];
}
return resuleArray;
}
持续更新中... 有不对的地方欢迎指正 🐝