#include <stdio.h>
#define MAXSIZE 10
typedef struct
{
int r[MAXSIZE + 1];
int length;
}SqList;
void InitSqList(SqList *L)
{
printf("please input the length of the sqlist:\n");
scanf("%d",&(L->length));
printf("please input the values of the sqlist:\n");
for (int index = 0; index < L->length; index++)
{
scanf("%d", &(L->r[index]));
}
}
void PrintSqList(SqList L)
{
for (int index = 0; index < L.length; index++)
{
printf("%d\n", L.r[index]);
}
printf("\n");
}
void swap(SqList *L, int i, int j)
{
int tem = L->r[i];
L->r[i] = L->r[j];
L->r[j] = tem;
}
//貌似是冒泡排序,不正宗
void BubbleSort0(SqList *L)
{
int firstIndex;
int secondIndex;
for (firstIndex = 0; firstIndex < L->length - 1; firstIndex++)
{
for (secondIndex = firstIndex + 1; secondIndex < L->length; secondIndex++)
{
if (L->r[firstIndex] > L->r[secondIndex]) //值一大就往后移动,自然是升序
{
swap(L, firstIndex, secondIndex);
}
}
}
}
//传统的冒泡排序,选择了三个比较区间,基本思想是一样的
void BubbleSort(SqList *L)
{
int firstIndex;
int secondIndex;
for (firstIndex = 0; firstIndex < L->length; firstIndex++)
{
for (secondIndex = L->length - 1; secondIndex > firstIndex; secondIndex--)
{
if (L->r[secondIndex] < L->r[secondIndex - 1])
{
swap(L, secondIndex, secondIndex - 1);
}
}
}
/*
for (firstIndex = 0; firstIndex < L->length; firstIndex++)
{
for (secondIndex = 1; secondIndex < L->length - firstIndex; secondIndex++)
{
if (L->r[secondIndex - 1] < L->r[secondIndex]) //如果前面数据小于后面的数据,就将二个数据交换,前面数永远不比后面数小,所以是从大到小排
{
swap(L, secondIndex - 1, secondIndex);
}
}
}*/
/*
for (firstIndex = 0; firstIndex < L->length - 1; firstIndex++)
{
for (secondIndex = L->length - 2; secondIndex >= firstIndex; secondIndex--)
{
if (L->r[secondIndex] < L->r[secondIndex + 1])
{
swap(L, secondIndex, secondIndex + 1);
}
}
}*/
}
#define TRUE 1
#define FALSE 0
typedef int Status;
void BubbleSort2(SqList *L)
{
int firstIndex = L->length;
int secondIndex;
Status flag = TRUE;
while (flag) //如果有一趟没有发生交换,说明排序已经完成
{
flag = FALSE;
for (secondIndex = 1; secondIndex < firstIndex; secondIndex++)
{
if (L->r[secondIndex - 1] < L->r[secondIndex])
{
swap(L, secondIndex - 1, secondIndex);
flag = TRUE; //有交换说明没有完成排序
}
}
firstIndex--;
}
}
void BubbleSort3(SqList *L)
{
int index;
int flag = L->length;
int maxIndex;
while (flag > 0)
{
maxIndex = flag;
flag = 0;
for (index = 1; index < maxIndex; index++)
{
if (L->r[index - 1] < L->r[index])
{
swap(L, index - 1, index);
flag = index; //for循环结束,flag位置之后的数据必定已经有序了,记录下这位置,第二次只要从数
//组头部遍历到这个位置就可以了
}
}
}
}
int main()
{
SqList L;
InitSqList(&L);
BubbleSort3(&L);
printf("after sorting ,the sqlist is:\n");
PrintSqList(L);
return 0;
}
《大话数据结构》读书笔记之冒泡排序和源码及优化算法源码
最新推荐文章于 2022-06-03 20:22:00 发布