回顾冒泡排序(新增优化代码)
// // main.c // 数组-冒泡排序 // // Created by LongMa on 2019/6/26. // Copyright © 2019. All rights reserved. // #include <stdio.h> int main(int argc, const char * argv[]) { int a[10]; for (int i = 0; i < 10; i++) { printf("请输入第%d个整数,共10个:",i + 1); scanf("%d", &a[i]); } int temp = 0; //冒泡:第一次,最大的排到了最后一位;第二次(不用对比最后一个),次大的排到倒数第二位... for (int i = 0; i <= 10 - 1 - 1 ; i++) {//共3个数,要循环2次 => n个数,循环n-1次 int endLoop = 0; for (int j = 0; j <= 10 - 1 - 1 - i ; j++) {//i为0时,j + 1最大 == 9,j最大 == 8 if (a[j] > a[j + 1]) { temp = a[j]; a[j] = a[j + 1]; a[j + 1] = temp; endLoop = 1; printf("exchanged\n"); } } printf("第%d次循环\n", i); //未发生过交换,说明已全部有序。结束循环 if (0 == endLoop) { break; } } for (int k = 0; k < 10; k++) { printf("%d\t",a[k]); } return 0; }
log:
请输入第1个整数,共10个:1 请输入第2个整数,共10个:2 请输入第3个整数,共10个:3 请输入第4个整数,共10个:4 请输入第5个整数,共10个:5 请输入第6个整数,共10个:6 请输入第7个整数,共10个:8 请输入第8个整数,共10个:7 请输入第9个整数,共10个:10 请输入第10个整数,共10个:9 exchanged exchanged 第0次循环 第1次循环 1 2 3 4 5 6 7 8 9 10 Program ended with exit code: 0
swift实现版
import Foundation func mp(arr: Array<Int>) ->Array<Int> { var a = arr let len = a.count for i in 0...(len - 2){ var endLoop = 0 for j in 0...(len - 2 - i){ if a[j] > a[j + 1] { //exchange let temp = a[j + 1] a[j + 1] = a[j] a[j] = temp endLoop = 1 print("exchanged") } } print("第\(i)次循环") if 0 == endLoop{ break; } } return a } let gArr : [Int] = [6, 3, 5, 4, 88, 9, 2, 1, 0] let lRslt = mp(arr: gArr) print(lRslt) print("---------") let gArr1 : [Int] = [1, 2, 3, 4, 5, 6, 8, 7, 9] let lRslt1 = mp(arr: gArr1) print(lRslt1)
log:
exchanged exchanged exchanged exchanged exchanged exchanged exchanged 第0次循环 exchanged exchanged exchanged exchanged 第1次循环 exchanged exchanged exchanged 第2次循环 exchanged exchanged exchanged 第3次循环 exchanged exchanged exchanged 第4次循环 exchanged exchanged exchanged 第5次循环 exchanged exchanged 第6次循环 exchanged 第7次循环 [0, 1, 2, 3, 4, 5, 6, 9, 88] --------- exchanged 第0次循环 第1次循环 [1, 2, 3, 4, 5, 6, 7, 8, 9]
学无止境,快乐编码。
没有一种不经过蔑视、忍受和奋斗就可以征服的命运。