一. 冒泡排序算法算法
1.第一次排序時將序列[0 ~ n - 1]中從前日後進行兩個相鄰元素的比較,若前者較大則交換,比較n-1次;
當第一趟排序結束時,序列最大的元素就被交換到位置n-1上,就如同一個氣泡,一步一步日後翻滾,直到最後一位。數組
2.重複步驟1,在第i趟時須要翻滾n-i-1次,每趟決定一個元素的位置,一共須要n-1趟。ui
好比,初始序列: [1, 5, 4, 3, 2]spa
第1趟: [1, 4, 3, 2 ] 5指針
第2趟: [1, 3, 2 ] 4, 5code
......blog
- (void)bubbleSort:(NSMutableArray *)array { int i, y; BOOL bFinish = YES; for (i = 1; i<= [array count] && bFinish; i++) { bFinish = NO; for (y = (int)[array count]-1; y>=i; y--) { if ([[array objectAtIndex:y] intValue] < [[array objectAtIndex:y-1] intValue]) { [array exchangeObjectAtIndex:y-1 withObjectAtIndex:y]; bFinish = YES; } } } }
2、簡單選擇排序算法排序
簡單選擇排序的基本思想:遞歸
1.第一趟在初始序列[0 ~ n-1]中找最小值元素,並與位置爲0的元素交換位置。get
2.第i趟在序列[i-1, n-1]中進行,找到最小值元素與位置爲i-1的元素交換位置。每次決定一個元素的位置,通過n-1趟後使得初始序列有序。
好比,初始序列:[1, 5, 4, 3, 2]
第1趟:1 [5, 4, 3, 2]
第2趟:1 2 [4, 3, 5]
......
- (void)selectSort:(NSMutableArray *)array { int i, j; for (i=0; i<array.count-1; i++) { int index = i; for (j = i+1; j<array.count; j++) { if ([array[j] intValue] < [array[index] intValue]) { index = j; } } [array exchangeObjectAtIndex:i withObjectAtIndex:index]; } }
3、快速排序算法 (reference : 百度百科)
/** 快速排序方法 @param array 源數組 @param startIndex 開始Index @param endIndex 結束Index */ -(void)quickSortDataArray:(NSMutableArray *)array withStartIndex:(NSInteger)startIndex andEndIndex:(NSInteger)endIndex{ //只是一個基本的判斷,若是數組長度爲0或1時返回。 if (startIndex >= endIndex) { return ; } NSInteger i = startIndex; NSInteger j = endIndex; //記錄比較基準數 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 quickSortDataArray:array withStartIndex:startIndex andEndIndex:i - 1]; //排序基準數右邊的 [self quickSortDataArray:array withStartIndex:i + 1 andEndIndex:endIndex]; }