跟我学数据结构:(2) 数组的遍历、插入和删除
摘要:
数组广泛的应用于各种数据结构和算法之中。本文通过代码演示了:
产生数组,遍历数组,查找数组中的最小值,在指定位置插入和删除元素。
本文仍然是作为学习数据结构的基础。
代码和运行结果
本课内容比较单纯,我们直接上代码,同学们可以多次运行代码,观察结果。
- /*
- desc: this program illustration how to use an array.
- */
- #include <iostream>
- #include<iomanip>
- #include<string>
- #include <math.h>
- #include <time.h>
- #include <cstdlib>
- using namespace std;
- const int MAX_SIZE = 10;
- int data[MAX_SIZE];
- int pos = 0;
- void showArray()
- {
- int i;
- for(i = 0; i < MAX_SIZE; i++)
- {
- cout << "/t data[ " << i << " ] = " << data[i] << endl;
- }
- cout << endl;
- }
- int main(int argc, char* argv[])
- {
- cout << argv[0]<< " start here" << endl;
- cout << " this program illustration how to use an array." << endl;
- cout << "initialize array by random numb:" << endl;
- srand((unsigned int)time(0));
- cout << " RAND_MAX = " << RAND_MAX<< endl;
- int i;
- for(i = 0; i < MAX_SIZE; i++)
- {
- ::data[i] = rand() % 100;
- }
- showArray();
- cout << " find out the minimum value in the array" << endl;
- int pos = 0;
- for(i = 1; i < MAX_SIZE; i++)
- {
- if (data[pos] > ::data[i])
- {
- pos = i;
- }
- }
- cout << " the minimum value in the array is "
- << "data[ " << pos << " ] = " << data[pos] << endl;
- cout << "generate a new position and new value, then insert it into the array"
- << endl;
- int newPos = rand() % MAX_SIZE;
- int newValue = rand() % 100;
- cout << "new pos = " << newPos << ", and new value = " << newValue << endl;
- for( i = MAX_SIZE-1; i > newPos; i--)
- {
- ::data[i] = ::data[i-1];
- }
- ::data[newPos] = newValue;
- showArray();
- cout << " generate a new position , and make the value is zero" << endl;
- newPos = rand() % MAX_SIZE;
- cout << " new pos = " << newPos << endl;
- ::data[newPos] = 0;
- showArray();
- cout << " let's delete the no. " << newPos << " element in the array,/n"
- << " and make the last value is minus one." << endl;
- for(int i = newPos; i <MAX_SIZE-1; i++)
- {
- ::data[i] = ::data[i+1];
- }
- ::data[MAX_SIZE-1] = -1;
- showArray();
- return 0;
- }
test start here
this program illustration how to use an array.
initialize array by random numb:
RAND_MAX = 32767
data[ 0 ] = 42
data[ 1 ] = 28
data[ 2 ] = 16
data[ 3 ] = 4
data[ 4 ] = 34
data[ 5 ] = 71
data[ 6 ] = 12
data[ 7 ] = 30
data[ 8 ] = 99
data[ 9 ] = 14
find out the minimum value in the array
the minimum value in the array is data[ 3 ] = 4
generate a new position and new value, then insert it into the array
new pos = 4, and new value = 53
data[ 0 ] = 42
data[ 1 ] = 28
data[ 2 ] = 16
data[ 3 ] = 4
data[ 4 ] = 53
data[ 5 ] = 34
data[ 6 ] = 71
data[ 7 ] = 12
data[ 8 ] = 30
data[ 9 ] = 99
generate a new position , and make the value is zero
|