Swift版
冒泡排序
//由大到小排列
let array = [2,34,64,73,32,76,45,54]
for i in 0..<array.count{
for j in 0..<array.count-1-i { //因为下面用j+1比较,所以需要array.count-1
if array[j] < array[j+1] { //如果要由小到大排列要改成>
let ts = array[j]
array[j] = array[j+1]
array[j+1] = ts
}
}
}
选择排序
//由大到小排列
let array = [2,34,64,73,32,76,45,54]
for i in 0..<array.count{
for j in i+1..<array.count {
if array[i] < array[j] { //如果要由小到大排列要改成>
let ts = array[i]
array[i] = array[j]
array[j] = ts
}
}
}
OC版
冒泡排序
//由大到小排列
NSMutableArray* array = [NSMutableArray arrayWithObjects:@1,@32,@43,@23,@12,@98,@65,@74,nil];
for (int i = 0; i<array.count; i++) {
for (int j = 0; j<array.count-1-i; j++) {
if (array[j] < array[j+1]) { //如果要由小到大排列要改成>
[array exchangeObjectAtIndex:j withObjectAtIndex:j+1];
}
}
}
选择排序
//由大到小排列
NSMutableArray* array = [NSMutableArray arrayWithObjects:@1,@32,@43,@23,@12,@98,@65,@74,nil];
for (int i=0; i<[array count]; i++) {
for (int j=i+1; j<[array count]; j++) {
if (array[i] < array[j]) { //如果要由小到大排列要改成>
[array exchangeObjectAtIndex:i withObjectAtIndex:j];
}
}
}












网友评论