基础排序--冒泡--选择--插入

1、冒泡排序

cpp 复制代码
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <stdbool.h>

//冒泡排序
void bubblesort(int q[],int N) 
{
	
	int temp = 0;
	for(int i = 0;i<N-1;i++)
	{
		for(int j = 0;j<N-i-1;j++)
		{
			if(q[j]>=q[j+1])  //注意这里不要写成j++ 
			{
				temp = q[j];
				q[j] = q[j+1];
				q[j+1] = temp;
			}
		}
	}
	
}


int main()
{
	int q[5] = {100,500,10,30,455};
	int n = sizeof(q) / sizeof(int);
	bubblesort(q,5);
	
	for(int i = 0;i<n;i++)
	{
		printf("%d ",q[i]);
	}
	
	return 0;
}

2、选择排序

外层大循环是n-1次 (因为是两两对比)

内层小循环是从第二个元素开始

思路:将当前未排序区间的第一个元素,设置为最小值

然后从第二个元素开始对比,然后将对比出的最小值,与这个区间的第一个元素交换即可

cpp 复制代码
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <stdbool.h>

//冒泡排序
void selectsort(int q[],int N) 
{
	int minIndex = 0;
	int temp;
	for(int i = 0;i<N-1;i++)
	{
		//假设未排序区间第一个元素是最小值
		minIndex = i;
		
		//从第二个元素开始对比 
		 for(int j = i+1;j<N;j++)
		 {
		 	if(q[j]<q[minIndex])
		 	{
		 		minIndex = j;
			 }
		 }
		 
		  // 将找到的最小值与未排序区间的第一个元素交换
		  temp = q[minIndex];
		  q[minIndex] = q[i];
		  q[i] = temp;
		 
		
	}
}



int main()
{
	int q[5] = {1,500,10,30,455};
	int n = sizeof(q) / sizeof(int);
	selectsort(q,5);
	
	for(int i = 0;i<n;i++)
	{
		printf("%d ",q[i]);
	}
	
	return 0;
}

3、插入排序

思路:将数组分为'已排序区间'和'未排序区间',每次从未排序区间取一个元素,插入到已排序区间的合适位置,直到所有元素排序完成

默认第一个元素已排序,从第二个元素开始

设立一个下标 J , 表示已排序区间的最后一位

如果 J 的值 大于当前要比较的值,那么我们将 q【j】这一位往后移,同时 j-- ,继续向前比较

如果不用再比较了,那么直接让q[j+1]这一位原来的 q【j】 的值变成current的值即可

cpp 复制代码
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <stdbool.h>

//插入排序
void insertsort(int q[],int n)
{
	int i,j,current;
	//未排序区间的第一个元素(从1开始,0号元素默认已排序)
	for(i=1;i<n;i++)
	{
		current = q[i];
		j = i-1;  //j是已排序区间末尾下标 
	
	//内层循环
	while(j>=0 && q[j] > current)
	{
		q[j+1] = q[j]; //元素后移一位 
		j--; //继续向前比较 
	 } 
	 
	   // 将current插入到正确位置(j+1是插入索引)
	   q[j+1] = current;
}
 } 

int main()
{
	int q[5] = {1,500,1022,30,455};
	int len = sizeof(q) / sizeof(q[0]);
	insertsort(q,len);
	
	for(int i = 0;i<len;i++)
	{
		printf("%d ",q[i]);
	}
	
	return 0;
}
相关推荐
THMAIL5 小时前
机器学习从入门到精通 - 卷积神经网络(CNN)实战:图像识别模型搭建指南
linux·人工智能·python·算法·机器学习·cnn·逻辑回归
shellvon5 小时前
用NCC识别验证码:一个简单但有效的Python实战思路
算法
Jiezcode5 小时前
Qt QJsonObject
c++·后端·qt
ZLRRLZ5 小时前
【数据结构】并查集
数据结构
没有bug.的程序员5 小时前
Redis 数据结构全面解析:从底层编码到实战应用
java·数据结构·redis·wpf
Lee嘉图5 小时前
数据结构——顺序表(Java)的基本操作
数据结构
金古圣人6 小时前
hot100 子串
数据结构·c++·算法·leetcode
LQ深蹲不写BUG7 小时前
深挖三色标记算法的底层原理
java·算法
BlackPercy7 小时前
【图论】Graphs.jl 最小生成树算法文档
算法·图论