绪论内容:
1.以冒泡排序为例进行算法的优化。
2.对于引用&的了解使用。(https://blog.youkuaiyun.com/u013203733/article/details/73868603)
3.静态数组中进行插入操作。
课上代码:
//算法的优化
#include<iostream>
using namespace std;
void bubble_sort(int a[],int n)
{
int i,j,t;
bool change;
//将a[]中的数字按照从小到大排序
for(i = n-1;i >= 1 /*&& change */;i--)
{
/* change=false;*/
for(j=1;j<i;j++)
{
if(a[j] < a[j+1])
{
//函数里真正对a[]执行操作的部分
t = a[j];
a[j] = a[j+1];
a[j+1] = t;
/* change = true;*/
}
}
}
}
void f(int &x)
{
x++;
}
typedef struct Arr{
char elem[101];
int lenth;
}Arr;//数据类型名称
typedef struct iArr{
char *elem;
int lenth;
int listsize;
}iArr;//动态数组(不定长数组)
int main()
{
int a=0;
//引用:&
int &r = a;//r是a的引用,外号。
//变量的作用范围(形式参数,返回值)
const int &c=a;
//只能通过别名访问变量的值,不能通过别名修改变量的值
cout<<a<<endl;
f(a);
cout<<a<<endl;
//函数引用参数,为实际参数起一个别名
Arr myFirstArr;
myFirstArr.elem[0]='1';
myFirstArr.elem[1]='2';
myFirstArr.elem[2]='o';
myFirstArr.elem[3]='k';
myFirstArr.lenth = 4;
//在数组中进行插入操作(在下标为2的位置插入3)
for(int i = myFirstArr.lenth - 1 ; i >= 2;i --)
myFirstArr.elem[i+1] = myFirstArr.elem[i];
//腾位置
myFirstArr.elem[2]='3';
//将元素插入
myFirstArr.lenth++;
//元素个数增加
for(int i=0;i<myFirstArr.lenth;i++)
cout<<myFirstArr.elem[i];
//输出数组元素
}
4.动态数组的初始化。
动态数组相比于静态数组可以方便数组容量进行动态扩充。
#include<iostream>
using namespace std;
#define LIST_INIT_SIZE 100
#define LISTINCREMENT 10
typedef struct {
char *elem;
int lenth;//当前数组的长度
int listsize;
}Sqlist;//动态数组的定义,结构体类型
Status Initlist(Sq_list &L){//Initlist(list)为实际参数list起一个别名L
//构造一个空的线性表,字符存放在elem指向的堆区的内存空间
L.elem = (char *)malloc(100*sizeof(char))//先申请内存空间,将申请的内存空间的起始地址放入elem中
if(!L.elem) exit(OVERFLOW); //开辟内存失败
listsize=100; //数组容量
L.lenth=0;//现有元素个数
return OK;
}
int main()
{
L.elem='1';
L.elem='2';
L.elem='o';
L.elem='k';
L.lenth=4;
for(int i = L.lenth - 1 ; i >= 2;i --)
L.elem[i+1] = L.elem[i];
//腾位置
L.elem[2]='3';
//将元素插入
L.lenth++;
//元素个数增加
for(int i=0;i<L.lenth;i++)
cout<<L.elem[i];
//输出数组元素
}
本文从冒泡排序的优化出发,探讨了引用&在算法中的应用,并详细讲解了静态数组的插入操作。同时,通过课上的代码示例,介绍了动态数组的初始化及其优势——能够根据需要动态扩充容量。
130

被折叠的 条评论
为什么被折叠?



