系列文章目录
前言🚗🚗🚗
冒泡排序
介绍
运行原理
基本概念
依次比较相邻的两个数,将小数放在前面,大数放在后面。
代码实现
#include<stdio.h>
typedef int Elemtype;
#define MAX 10
typedef struct
{
int *arr;
int length;
}num;
num Sort_bobble(int *arr,int n){
int end = n;
int i = 0;
while (end)
{
int flag = 0;
for (i = 1;i < end;i++)
{
if (arr[i - 1] > arr[i])
{
/* int tem = arr[i];
arr[i] = arr[i - 1];
arr[i - 1] = tem;*/
swap(&arr[i], &arr[i - 1]);
flag = 1;
}
}
if (flag == 0)
break;
end--;
}
num retult = { arr,n };
return retult;
}//冒泡排序
int main()
{
int arr[MAX] = { 2,3,4,5,1,3 };
int n = 6;
int i = 0;
num retult = Sort_bobble(arr, n);
for(i = 0;i < retult.length;i++)
{
printf("%d",retult.arr[i]);
}
return 0;
}
插入排序
介绍
运行原理
基本概念
代码实现
#include<stdio.h>
typedef int Elemtype;
#define MAX 10
typedef struct
{
int *arr;
int length;
}num;
void swap(int* a, int* b)
{
int tem = *a;
*a = *b;
*b = tem;
}//交换位置
num Sort_insert(int * arr, int n) {
int i = 0;
for (i = 0;i < n - 1 ;++i)
{
int end = i;
int tem = arr[end + 1];
while (end >= 0)
{
if (tem < arr[end])
{
arr[end + 1] = arr[end];
end--;
}
else
break;
}
arr[end + 1] = tem;
}
num result = { arr,n };
return result;
}//插入排序
int main()
{
int arr[MAX] = { 2,3,4,5,1,3 };
int n = 6;
int i = 0;
num retult = Sort_insert(arr, n);
for(i = 0;i < retult.length;i++)
{
printf("%d",retult.arr[i]);
}
return 0;
}
选择排序
介绍
运行原理
基本概念
代码实现
#include<stdio.h>
typedef int Elemtype;
#define MAX 10
typedef struct
{
int *arr;
int length;
}num;
num Sort_selection(int* arr, int n)
{
int i = 0;
int begin = 0, end = n - 1;
while (begin < end)
{
int max = begin;
int min = begin;
for (i = begin;i <= end;i++)
{
if (arr[i] < arr[min])
min = i;
if (arr[i] > arr[max])
max = i;
}
swap(&arr[min], &arr[begin]);
if (begin == max)
max = min;
swap(&arr[max], &arr[end]);
++begin;
--end;
}
num retult = { arr,n };
return retult;
}//选择排序
int main()
{
int arr[MAX] = { 2,3,4,5,1,3 };
int n = 6;
int i = 0;
num retult = Sort_selection(arr, n);
for(i = 0;i < retult.length;i++)
{
printf("%d",retult.arr[i]);
}
return 0;
}