zoukankan      html  css  js  c++  java
  • 数据结构与算法之数组(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.
    ');
    21   } else {
    22     print('found the key at: $pos.
    ');
    23   }
    24 
    25   var oldValue = _modify(_length ~/ 2, _rnd.nextInt(_max));
    26   if (oldValue != null) {
    27     print('has modified! and oldValue is $oldValue.
    ');
    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
    ');
    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!
    ');
    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!
    ');
    80   } else {
    81     print('the index of deleted key is: $pos
    ');
    82     for (var i = pos; i < _length - 1; i++) {
    83       _array[i] = _array[i + 1];
    84     }
    85     _length--;
    86   }
    87 }

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

  • 相关阅读:
    go 字符串转换
    GRU模型结构
    ElasticSearch实战系列八: Filebeat快速入门和使用---图文详解
    H5可视化编辑器(H5 Dooring)
    (转)如何防止Axios对我的请求参数进行编码?
    vue使用element-ui,如何给Label加标签
    vue中$router.push打开新窗口
    (转)webstorm配置svn
    打开gitee.com网站报错
    监控$route无效
  • 原文地址:https://www.cnblogs.com/outerspace/p/10233680.html
Copyright © 2011-2022 走看看