当前位置:网站首页>选择法排序与冒泡法排序【C语言】
选择法排序与冒泡法排序【C语言】
2022-07-06 09:16:00 【薇远镖局】
1、选择法排序
/*
选择法排序:由小到大
工作原理如下:首先在未排序序列中找到最小(大)元素,存放到排序序列的起始位置,
然后,再从剩余未排序元素中继续寻找最小(大)元素,然后放到已排
序序列的末尾。以此类推,直到所有元素均排序完毕。
*/
void sel_sort_s2b(int arr[], int n)
{
int min;
int temp;
for (int i = 0; i<(n - 1); i++)
{
min = i;
for (int j = i + 1; j<n; j++)
{
if (arr[min] > arr[j])
{
min = j; //将数组中最小值的下标记录下来
}
}
if (min != i) //min等于i的话不需要交换
{
temp = arr[i];
arr[i] = arr[min];
arr[min] = temp;
}
}
}
/*
选择法排序:由大到小
工作原理如下:首先在未排序序列中找到最大(小)元素,存放到排序序列的起始位置,
然后,再从剩余未排序元素中继续寻找最大(小)元素,然后放到已排
序序列的末尾。以此类推,直到所有元素均排序完毕。
*/
void sel_sort_b2s(int a[], int len)
{
#define SWAP(X,Y) X=X+Y;Y=X-Y;X=X-Y
int max;
for (int i = 0; i < len - 1; i++)
{
max = i;
for (int j = i + 1; j < len; j++)
{
if (a[j] > a[max])
{
max = j;
}
}
if (max != i)
{
SWAP(a[i], a[max]);
}
}
}2、冒泡法排序
/*
冒泡法排序:由小到大
工作原理如下:它重复地走访过要排序的数列,一次比较两个元素,如果他们的顺序(如从大到小、首字母从A到Z)错误就把他们交换过来。
*/
void bubble_sort_s2b(int arr[], int len)
{
#define SWAP(X,Y) X=X+Y;Y=X-Y;X=X-Y
for (int i = 0; i<(len - 1); i++)
{
for (int j = 0; j<(len - i - 1); j++)
{
if (arr[j] > arr[j + 1])
{
SWAP(arr[j], arr[j + 1]);
}
}
}
}
/*
冒泡法排序:由大到小
工作原理如下:它重复地走访过要排序的数列,一次比较两个元素,如果他们的顺序(如从大到小、首字母从A到Z)错误就把他们交换过来。
*/
void bubble_sort_b2s(int arr[], int len)
{
#define SWAP(X,Y) X=X+Y;Y=X-Y;X=X-Y
for (int i = 0; i<(len - 1); i++)
{
for (int j = 0; j<(len - i - 1); j++)
{
if (arr[j] < arr[j + 1])
{
SWAP(arr[j], arr[j + 1]);
}
}
}
}
边栏推荐
猜你喜欢

vs2019 桌面程序快速入门

PHP - whether the setting error displays -php xxx When PHP executes, there is no code exception prompt

About string immutability

Password free login of distributed nodes

【flink】flink学习

E-commerce data analysis -- User Behavior Analysis

FTP文件上传文件实现,定时扫描文件夹上传指定格式文件文件到服务器,C语言实现FTP文件上传详解及代码案例实现

Small L's test paper

Word排版(小計)
![[Blue Bridge Cup 2017 preliminary] grid division](/img/e9/e49556d0867840148a60ff4906f78e.png)
[Blue Bridge Cup 2017 preliminary] grid division
随机推荐
SQL time injection
JS array + array method reconstruction
[NPUCTF2020]ReadlezPHP
Valentine's Day flirting with girls to force a small way, one can learn
Wangeditor rich text reference and table usage
2020 WANGDING cup_ Rosefinch formation_ Web_ nmap
Nanny level problem setting tutorial
Composition des mots (sous - total)
MySQL and C language connection (vs2019 version)
Kept VRRP script, preemptive delay, VIP unicast details
Internet protocol details
Connexion sans mot de passe du noeud distribué
数据分析之缺失值填充(重点讲解多重插值法Miceforest)
XML文件详解:XML是什么、XML配置文件、XML数据文件、XML文件解析教程
Mall project -- day09 -- order module
Correspondence between STM32 model and contex M
快来走进JVM吧
Aborted connection 1055898 to db:
ES6 let and const commands
4. Install and deploy spark (spark on Yan mode)