最经典的入门排序算法,冒泡排序,dart语言实现。数组仍然采用随机生成的数组,使用dart内置的List 的generate方法,排序前后分别打印出数组,以观察效果。
1 import 'dart:math' show Random; 2 3 void main() { 4 final seed = 100, rnd = Random(), length = 100; 5 var list = 6 List<int>.generate(length, (i) => rnd.nextInt(seed), growable: false); 7 print(list); 8 print('-------'); 9 bubbleSort(list); 10 print(list); 11 } 12 13 void bubbleSort(List<int> a) { 14 for (var i = a.length; i > 0; i--) 15 for (var j = 0; j < i - 1; j++) 16 if (a[j] > a[j + 1]) { 17 var t = a[j + 1]; 18 a[j + 1] = a[j]; 19 a[j] = t; 20 } 21 }