栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

排序算法合集(冒泡,选择,插入)

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

排序算法合集(冒泡,选择,插入)

一、冒泡排序:

        每一次从前往后循环,每一次将当前区域内的最大值通过交换的方式交换到最后的位置上。

        如:

        a[9] = { 9,4, 5, 6, 1, 2, 3, 7, 8};

        第一次循环将 9 交换到最后的位置上:a[9] = {4, 5, 6, 1, 2, 3, 7, 8, 9};

        然后再通过 n 次循环,每次循环的长度 -1 

        即:

        第二次循环将a[8] = {4, 5, 6, 1, 2, 3, 7, 8};内的最大值交换到最后面的位置上。

        第三次循环将a[7] = {4, 5, 6, 1, 2, 3, 7};内的最大值交换到最后面的位置上。 

        以此类推

#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
using namespace std;
int a[9] = {4, 5, 6, 1, 2, 3, 7, 8, 9};
void sort() {
	for (int i = 8; i >= 0; i--) {
		for (int j = 0; j < i; j++) {
			if (a[j] > a[j + 1]) {
				int temp = a[j];
				a[j] = a[j + 1];
				a[j + 1] = temp;
			}
		}
	}
}
int main() {
	sort();
	for (int i = 0; i < 9; i++) {
		printf("%dn", a[i]);
	}
	return 0;
}
二、选择排序:         核心思想:

                找到当前数组内的最大值,将此最大值和最后一个位置的数值进行交换

        步骤:

        1、找最大值(寻找并记录最大值下标):

        (1)首先将 0 下标定为最大值下标

        (2)从前往后循环,遇到大于当前最大值的数,就将遇到的最大值下标定为记录的最大值下标

        2、将当前最大值的下标与区间的最后一位进行数值交换。

        3、重复步骤1、2,依次寻找第2、3、4....大的数! 

#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
using namespace std;
int a[9] = {4, 5, 6, 1, 2, 3, 7, 8, 9};
void sort() {
	for (int i = 8; i >= 0; i--) {
		int max = i;//最开始时最大值的下标
		for (int j = 0; j < i; j++) {
			if (a[max] < a[j])//如果在寻找过程中存在比当前最大值大的数
				max = j;//将最大值下标更改
		}
		if (max != i) {//如果最大值下标和最初的值不一样,最大值的下标有改变,需要交换
			int temp = a[i];
			a[i] = a[max];
			a[max] = temp;
		}
	}
}
int main() {
	sort();
	for (int i = 0; i < 9; i++) {
		printf("%dn", a[i]);
	}
	return 0;
}
 三、插入排序         核心思想:

                当数字是一个数时,我们认为这个数是有序的,将当前数字插入到合适的位置上,如果当前位置的值小于前面的值,就和前面的值进行交换,直到前面的数字比当前数字小或下标为 0 为止。

        如:

            4,7,5

        (1)4这个数字是有序的

        (2)4,7   7这个数字比4大,所以,4,7也是有序的

        (3)4,7,5 

                这个时候,我们可以想,根据(2)我们可以知道:5前面的数字是有序的,我们将5比7小,我们将其交换得:4,5,7  此时,5比7小,5比4大,所以4,5,7是一个有序得数组插入排序就完成了

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/879507.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号