僅用于個人學(xué)習(xí)記錄踢星,代碼不是最優(yōu)寫法橘沥,只是方便記錄算法思想喉祭,會持續(xù)更新
鏈表
1、鏈表
- 查找
- 插入
- 移除
2炮沐、棧(先進后出,尾部添加或刪除元素)
- push(入棧)
- pop(出棧)
- peek(獲取頂部值)
3回怜、隊列(先進先出大年,尾部添加元素,頭部刪除元素)
- enqueue(入隊)
- dequeue(出隊)
- peek(獲取頂部值)
4玉雾、雙鏈表(與鏈表區(qū)別在于翔试,雙向指針)
- 查找
- 插入
- 移除
5、雙端隊列(與棧和隊列的區(qū)別抹凳,首尾都能添加元素遏餐,首尾均能出列)
- enqueue(入隊)
- dequeue(出隊)
- peek(獲取頂部值)
排序算法
- 冒泡排序
/*
* 冒泡排序,相鄰兩個對比赢底,前者比后者大失都,交換位置
*
*/
-(void)bubbleSort{
NSMutableArray *array = [NSMutableArray arrayWithArray:@[@3,@44,@38,@5,@47,@15,@36,@26,@27,@2,@46,@4,@19,@50,@49]];
BOOL swapped = NO;
do {
swapped = NO;
for (int i = 1; i < array.count; i++) {
NSInteger num1 = [array[i-1] integerValue];
NSInteger num2 = [array[i] integerValue];
if (num1 >num2) {
[array replaceObjectAtIndex:i-1 withObject:[NSNumber numberWithInteger:num2]];
[array replaceObjectAtIndex:i withObject:[NSNumber numberWithInteger:num1]];
swapped = YES;
}
}
} while (swapped);
NSLog(@"冒的排序:%@",array);
}
- 選擇排序
/*
* 選擇排序,標(biāo)記最小值幸冻,循環(huán)比較粹庞,替換最小值
*
*/
-(void)selectionSort{
NSMutableArray *array = [NSMutableArray arrayWithArray:@[@3,@44,@38,@5,@47,@15,@36,@26,@27,@2,@46,@4,@19,@50,@49]];
NSInteger repeatTimes = array.count -1;
int sortBeginIndex = 0;//開始對比下標(biāo)
do {
int miniNumIndex = sortBeginIndex;
NSInteger miniNum = [array[sortBeginIndex] integerValue];
for (int i = sortBeginIndex +1; i < array.count; i++) {
NSInteger selectNum = [array[i] integerValue];
if (selectNum < miniNum) {
miniNum = selectNum;
miniNumIndex = i;
}
}
[array replaceObjectAtIndex:miniNumIndex withObject:array[sortBeginIndex]];
[array replaceObjectAtIndex:sortBeginIndex withObject:[NSNumber numberWithInteger:miniNum]];
sortBeginIndex ++;
repeatTimes --;
} while (repeatTimes > 0);
NSLog(@"選擇排序:%@",array);
}
- 插入排序
/*
* 插入排序,逐個元素拿出來洽损,與其左邊元素逐個對比庞溜,碰到比該元素小的元素,則插入在對比元素后
*
*/
-(void)insertionSort{
NSMutableArray *array = [NSMutableArray arrayWithArray:@[@3,@44,@38,@5,@47,@15,@36,@26,@27,@2,@46,@4,@19,@50,@49]];
int sortBeginIndex = 1;//開始對比下標(biāo)
do {
NSInteger sortBeginNum = [array[sortBeginIndex] integerValue];
[array removeObjectAtIndex:sortBeginIndex];
for (int i = sortBeginIndex -1; i >= 0; i--) {
NSInteger compareNum = [array[i] integerValue];
if (compareNum < sortBeginNum) {
[array insertObject:[NSNumber numberWithInteger:sortBeginNum] atIndex:i+1];
break;
}else{
if (i==0) {
[array insertObject:[NSNumber numberWithInteger:sortBeginNum] atIndex:0];
}
}
}
sortBeginIndex ++;
} while (sortBeginIndex < array.count);
NSLog(@"插入排序:%@",array);
}