1.冒泡排序算法
/**
冒泡排序算法
@param mutableArray 需要排序的數組
*/
- (void)bubbleSortArray:(NSMutableArray *)mutableArray {
for (int i = 0; i < mutableArray.count; i ++) {
for (int j = 0; j < mutableArray.count - 1; j ++) {
if (mutableArray[j] > mutableArray[j + 1]) {
[mutableArray exchangeObjectAtIndex:j withObjectAtIndex:j + 1];
}
}
}
}```
### 2.選擇排序算法
```OC
/**
選擇排序算法
@param mutableArray 需要排序的數組
*/
- (void)selectionSortArray:(NSMutableArray *)mutableArray {
for (int i = 0; i < mutableArray.count; i ++) {
for (int j = i + 1; j < mutableArray.count; j ++) {
if (mutableArray[i] > mutableArray[j]) {
[mutableArray exchangeObjectAtIndex:i withObjectAtIndex:j];
}
}
}
}```
#### 3.快速排序算法
```OC
/**
快速排序算法
@param array 需要排序的數組
@param leftIndex 左邊的下標
@param rightIndex 右邊的下標
*/
- (void)quickSortArray:(NSMutableArray *)array
leftIndex:(NSInteger)leftIndex
rightIndex:(NSInteger)rightIndex {
if (leftIndex >= rightIndex) {
return ;
}
NSInteger i = leftIndex;
NSInteger j = rightIndex;
// 記錄基準數
NSInteger key = [array[i] integerValue];
while (i < j) {
// 首先從右邊j開始查找比基準數小的值
while (i < j && [array[j] integerValue] >= key) {
j --;
}
// 如果比基準數小,則將查找到的小值調換到i的位置
array[i] = array[j];
// 當在右邊查找到一個比基準數小的值時,就從i開始往后找比基準數大的值
while (i < j && [array[i] integerValue] <= key) {
i++;
}
// 如果比基準數大,則將查找到的大值調換到j的位置
array[j] = array[i];
}
// 將基準數放到正確位置
array[i] = @(key);
// 遞歸排序
[self quickSortArray:array leftIndex:leftIndex rightIndex:i - 1];
[self quickSortArray:array leftIndex:i + 1 rightIndex:rightIndex];
}```
最后編輯于 :
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。