//冒泡排序的优化
int array10[] = { 9, 7, 3, 8, 4};
BOOL flag1 = YES;
for (int i = 0; i < 5 - 1 && flag1; i++) {
flag = NO;//假设本趟循环没有做交换
for (int j = 0; j < 5 - 1 - i; j++) {
if (array10[j] > array10[j + 1]) {
int temp = array10[j];
array10[j] = array10[j + 1];
array10[j + 1] = temp;
flag1 = YES;//交换就置成YES
}
}
}Swift语言中//冒泡排序
var sortBubble = [12, 45, 2, 8, 74, 10]
for var i = 0; i < sortBubble.count - 1; i++ {
for var j = 0; j < sortBubble.count - 1 - i; j++ {
if sortBubble[j] < sortBubble[j + 1] {
var temp : Int = sortBubble[j]
sortBubble[j] = sortBubble[j + 1]
sortBubble[j + 1] = temp
}
}
}
sortBubble
// 冒泡排序的优化
var flag : Bool = true
for var i = 0; i < sortBubble.count - 1 && flag; i++ {
flag = false
for var j = 0; j < sortBubble.count - 1 - i; j++ {
if sortBubble[j] < sortBubble[j + 1] {
var temp : Int = sortBubble[j]
sortBubble[j] = sortBubble[j + 1]
sortBubble[j + 1] = temp
flag = true } } }
2 选择排序 //选择排序 思想: 每次选择当前序列中的最大值
NSMutableArray *sortSelect = [NSMutableArray arrayWithObjects:@12, @25, @0, @31, @20, nil];
int m,n; NSNumber *temp;
for (m = 0; m < sortSelect.count - 1; m++) {
for (n = m + 1; n < sortSelect.count; n++) {
if (sortSelect[n] < sortSelect[m]) {
temp = sortSelect[n];
sortSelect[n] = sortSelect[m];
sortSelect[m] = temp; } } }
for (NSNumber *num in sortSelect) {
NSLog(@"%@", num); }
Swift语言中 var sortSelsect = [12, 25, 3, 86, 20, 4, 12]for var i = 0; i < sortSelsect.count - 1; i++ {
for var j = i + 1; j < sortSelsect.count; j++ {
if sortSelsect[j] < sortSelsect[i] {
var temp = sortSelsect[j]
sortSelsect[j] = sortSelsect[i]
sortSelsect[i] = temp } } }
sortSelsect