冒泡排序思想:两两比较相邻的关键字,如果反序则交换,直到没有反序的记录为止。
- (NSArray*)paiXuMaoPao:(NSArray*)demoArr{
NSMutableArray *arr = [NSMutableArray arrayWithArray:demoArr];
for(inti =0; i< arr.count-1; i++) {
for(intj =0; j< arr.count- i -1; j++) {
if([arr[j]integerValue] > [arr[j+1]integerValue]) {
[arrexchangeObjectAtIndex:j withObjectAtIndex:j+1];
}
}
}
return[arrcopy];
}
时间复杂度:O(n²)
快速排序:1.选出索引第一个元素leftIndex和最后一个元素rightIndex,并把第一个元素作为key
2.从第一个元素向左找到比第一个元素小的的并交换位置leftIndex,如果没找到则向右遍历出比key大的数交换位置,此时结束了一次循环,此时key左边的元素都比它小,key右边的元素比他大
3.分别对key左右进行对比,找不到则结束循环
- (void)quietPaixu:(NSMutableArray*)demoArr leftIndex:(NSInteger)leftIndex rightIndex:(NSInteger)rightIndex
{
// NSMutableArray *arr = [NSMutableArray arrayWithArray:demoArr];
if(leftIndex >= rightIndex) {
// demoArr = arr;
return;
}
NSIntegeri = leftIndex;
NSIntegerj = rightIndex;
NSIntegerkey = [demoArr[i]integerValue];
while(i < j) {
while(i< j && [demoArr[j]integerValue] >= key) {
j -- ;
}
// arr[i] = arr[j];
if([demoArr[j]integerValue] < key) {
[demoArrexchangeObjectAtIndex:i withObjectAtIndex:j];
}
while(i< j && [demoArr[i]integerValue] <= key) {
i++;
}
if([demoArr[i]integerValue] > key) {
[demoArrexchangeObjectAtIndex:j withObjectAtIndex:i];
}
}
[selfquietPaixu:demoArrleftIndex:leftIndexrightIndex:i-1];
[selfquietPaixu:demoArrleftIndex:i+1rightIndex:rightIndex];
}
有序数组的排序
/*1.创建一个nil数组装2个数组合集
2.循环比较2个数组的第一个元素,小的加入空数组,然后在对应的数组中删除这个元素,再循环做比较
3.当一个数组为的数量为0的时候把例外一个数组的元素放入其中
*/
- (NSArray*)combineOneArr:(NSArray*)oneArr twoArr:(NSArray*)twoArr
{
NSMutableArray *comArr = [NSMutableArray new];
NSMutableArray *oneMArr = [NSMutableArray arrayWithArray:oneArr];
NSMutableArray *twoMArr = [NSMutableArray arrayWithArray:twoArr];
intcount = (int)oneArr.count+ (int)twoArr.count;
for(inti =0; i< count; i++) {
if([oneMArr[0]integerValue] > [twoMArr[0]integerValue]) {
[comArraddObject:twoMArr[0]];
[twoMArrremoveObject:twoMArr[0]];
}else{
[comArraddObject:oneMArr[0]];
[oneMArrremoveObject:oneMArr[0]];
}
if(oneMArr.count==0) {
[comArraddObjectsFromArray:twoMArr];
returncomArr;
}
if(twoMArr.count==0) {
[comArraddObjectsFromArray:oneMArr];
returncomArr;
}
}
return nil;
}