一.排序的定义:
代码实现:
1.冒泡排序:
//冒泡排序:
void BubbleSort(SqList &L)
{
int i, j;
for (i = 1; i < L->length; i++)
{
for (j = L -> length - 1; j > i; j--)
{
if (L->r[j] > L->r[j+1])
{
swap(L, j, j + 1);
}
}
}
}
改进flag:
//冒泡改进
void BubbleSort(SqList &L)
{
int i, j;
bool flag = true; //标记
for (i = 1; i < L->length && flag; i++)
{
flag = false;//初始化
for (j = L->length - 1; j > i; j--)
{
if (L->r[j] > L->r[j + 1])
{
swap(L, j, j + 1);
flag = true;//有交换flag为true
}
}
}
}
2.简单选择排序:
//2选择排序
void SelectSort(SqList &L)
{
int i, j, min;
for (i = 1; i < L->length; i++)
{
min = i;//已经排好的末尾
for (j = i + 1; j <= L->length; j++)//未排序序列
{
if (L - r[min] > L->r[j])
min = j; //找出未排序序列中的最小值
}
if (i != min)
swap(L, i, j);//交换
}
}
3.直接插入排序:
1.直接插入
void insert_sort(int a[])
{
int i,j,temp;
for(i=1;i<n;i++)
{
temp=a[i]; //暂时存储下标为1的数
for(j=i-1;j>=0&&temp<a[j];j--)
{
a[j+1]=a[j]; //满足条件就往后移
}
a[j+1]=temp;
}
}
public static void insertSort2(int []input){
for(int i=1;i<input.length;i++){
for(int j=i-1;j>=0;j--){
//基于有i前面的元素数有序的,交换之后input[i]的值向前移动了一位,直到有input[j]<input[j+1]为止
if(input[j]>input[j+1]){
int temp = input[j];
input[j] = input[j+1];
input[j+1] = temp;
}
}
}
}
4.希尔排序:
//希尔排序:
void shell_sort(int arry[],int len)
{
int i,j,temp,h;
for(h=len/2;h>0;h/2) //控制增量步
{
for(i=h;i<len;i++)
{
temp=a[i];
for(j=i-h;j>=0&&temp<a[j];j-=h)
{
a[j+h]=a[j];
}
a[j+h]=temp;
}
6.快速排序:
void Qsort(int a[],int low,int high)
{
int pivot;
if(low<high)
{
pivot=Partition(L,low,high);//一份唯二
Qsort(a[],low,pivot-1); //对低子表递归
Qsort(a[],pivot+1,high); //对高子表递归
}
}
int Partition(int a[],int low,int high)
{
int privotkey;
privotkey=a[low];//用表的最后一个当做枢轴
while(low!=high) //从表的两端向中间扫描
{
while(low<high && a[high]>=privoty)
high--;
a[low]=a[high];
while(low<high && a[low]<=privoty)
low++;
a[high]=a[low];
}
return low;
}
5.堆排序
6.归并:
视频:https://www.bilibili.com/video/av15962030?from=search&seid=12403747455520917007
//L=左边的起始位置 R=右边的起始位置,RightEnd=右边的终点
void Merge(ElementType A[],ElementType TmpA[],int L,int R,int RightEnd)
{
LeftEnd = R-1;//左边终点位置,假设左右两边挨着
Tmp = L; //存放结果的数组的起始位置
NumElements = RightEnd-L-1;
while(L<=LeftEnd && R<=RightEnd)
{
if(A[L] <= A[R]) //比较左右大小
TmpA[Tmp++] = A[L++];
else
TmpA[Tmp++] = A[R++];
}
//那边剩下直接存在后面
while(L<=LeftEnd)
TmpA[Tmp++]=A[L++];
while(R<=RightEnd)
TmpA[Tmp++]=A[R++];
//将TmpA导入A中
for(int i=0;i<NumElements;i++,RightEnd--)
A[RightEnd]=TmpA[RightEnd];
}
//递归
void MSort(ElementType A[],ElementType TmpA[],int L,int RightEnd)
{
int center;
if(L<RightEnd)
{
center=(L+RightEnd)/2;
MSort(A,TmpA,L,center);
MSort(A,TmpA,center+1,RightEnd);
Merge(A,TmpA,L,center+1,RightEnd);
}
}
//函数接口
void Merge_sort(ElementType A[],int n)
{
ElementType *TmpA;
TmpA = malloc(N*sizeof(ElementType));
if(TmpA != NULL)
{
MSort(A,TmpA,0,N-1);
free(TmpA);
}
else
Error("空间不足");
}
参考 资料:
《大话数据结构》
B站视屏
优快云:https://blog.youkuaiyun.com/u011815404/article/details/79284948