数据结构与算法之数组(1)——in dart


 1 import 'dart:math' show Random;
 2 
 3 List<int> _array;
 4 final _rnd = Random();
 5 final _capacity = 100;
 6 final _max = 100;
 7 var _length = 0;
 8 
 9 void main() {
10   _array = List<int>(_capacity);
11   // _array = List<int>.filled(_capacity, -1);
12 
13   _insert();
14   _display();
15 
16   var key = _rnd.nextInt(_max);
17   print('the find key is: $key');
18   var pos = _find(key);
19   if (pos < 0) {
20     print('can not find the key: $key.\n');
21   } else {
22     print('found the key at: $pos.\n');
23   }
24 
25   var oldValue = _modify(_length ~/ 2, _rnd.nextInt(_max));
26   if (oldValue != null) {
27     print('has modified! and oldValue is $oldValue.\n');
28   }
29   _display();
30 
31   _delete(_rnd.nextInt(_max));
32   _display();
33 }
34 
35 void _insert() {
36   for (var i = 0; i < _capacity ~/ 2; i++) {
37     _array[i] = _rnd.nextInt(_max);
38     _length++;
39   }
40 }
41 
42 void _display() {
43   var sb = StringBuffer();
44   for (var i = 0; i < _length; i++) {
45     sb.write('${_array[i]}, ');
46   }
47   var s = sb.isEmpty ? '' : sb.toString().substring(0, sb.length - 2);
48   print('$s\n');
49 }
50 
51 int _find(int key) {
52   var index = -1;
53   for (var i = 0; i < _length; i++) {
54     if (_array[i] == key) {
55       index = i;
56       break;
57     }
58   }
59   return index;
60 }
61 
62 int _modify(int pos, int newValue) {
63   int oldValue;
64   if (pos > _length - 1) {
65     print('out of bound!\n');
66   } else {
67     print(
68         'will modify the value(${_array[pos]}) of array[$pos] to new value: $newValue');
69     oldValue = _array[pos];
70     _array[pos] = newValue;
71   }
72   return oldValue;
73 }
74 
75 void _delete(int key) {
76   print('the deleted key is: $key');
77   var pos = _find(key);
78   if (pos < 0) {
79     print('can not find the key: $key!\n');
80   } else {
81     print('the index of deleted key is: $pos\n');
82     for (var i = pos; i < _length - 1; i++) {
83       _array[i] = _array[i + 1];
84     }
85     _length--;
86   }
87 }

这是用dart语言实现的数组,因为dart内置List,且面向对象,本代码故意没有使用类和内置的List的部分特性。为了保证运行效果,采用随机数进行增删改查。

优质内容筛选与推荐>>
1、【CQOI2017】小Q的表格
2、vue项目中 axios 和Vue-axios的关系
3、node.js module初步理解
4、python循环结构注意点
5、图片下载&&非同源图片下载&&同源下载&&网页点击下载图片


长按二维码向我转账

受苹果公司新规定影响,微信 iOS 版的赞赏功能被关闭,可通过二维码转账支持公众号。

    阅读
    好看
    已推荐到看一看
    你的朋友可以在“发现”-“看一看”看到你认为好看的文章。
    已取消,“好看”想法已同步删除
    已推荐到看一看 和朋友分享想法
    最多200字,当前共 发送

    已发送

    朋友将在看一看看到

    确定
    分享你的想法...
    取消

    分享想法到看一看

    确定
    最多200字,当前共

    发送中

    网络异常,请稍后重试

    微信扫一扫
    关注该公众号