冒泡排序
时间复杂度为O(n2)
/*************冒泡排序*************/
void BubbleSort(int r[], int n)
{
int i, j,flag,temp;
for (i = n - 1; i >= 1; i--)
{
flag = 0;
for (j = 1; j <= i; j++)
{
if (r[j - 1] > r[j])
{
temp = r[j];
r[j] = r[j - 1];
r[j - 1] = temp;
flag = 1;
}
}
}
printf("冒泡排序后序列为:");
for (int m = 0; m < n; m++)
printf("%d ", r[m]);
}
快速排序
快速排序是对冒泡排序的一种改进
时间复杂度最坏情况下是O(n2),但一般情况下,快速排序的时间复杂度是O(nlog2n)
/***********快速排序***********/
void QuickSort(int r[],int low,int high)
{
int i;
if (low < high)
{
int pivotpos = Partition(r, low, high);
QuickSort(r, low, pivotpos-1);
QuickSort(r, pivotpos + 1, high);
}
}
void Print(int r[])
{
printf("\n快速排序后序列为:");
for (int i = 0; i < count; i++)
printf("%d ", r[i]);
}
//快速排序的划分操作版本
int Partition(int r[],int low,int high)
{
int pivot = r[low]; //将当前表中第一个元素设为基准,对表进行划分
while (low < high)
{
while (low < high && r[high] >= pivot)
--high;
r[low] = r[high];//将比基准小的元素移到左端
while (low < high && r[low] <= pivot)
++low;
r[high] = r[low]; //将比基准大的元素移动到右端
}
r[low] = pivot; //基准元素存放到最终位置
return low; //返回存放基准值的最终位置
}
完整版本代码
#include <stdio.h>
#define maxSize 100
int R[maxSize] = { 0 };
int count = 0;
void Indata()
{
int i = 0;
printf("请输入整数数据(按回车键结束输入):");
while (1)
{
scanf_s("%d", &R[i]);
i++;
count++;
char c = getchar();
if ('\n' == c)
break;
}
}
/*************冒泡排序*************/
void BubbleSort(int r[], int n)
{
int i, j,flag,temp;
for (i = n - 1; i >= 1; i--)
{
flag = 0;
for (j = 1; j <= i; j++)
{
if (r[j - 1] > r[j])
{
temp = r[j];
r[j] = r[j - 1];
r[j - 1] = temp;
flag = 1;
}
}
}
printf("冒泡排序后序列为:");
for (int m = 0; m < n; m++)
printf("%d ", r[m]);
}
/***********快速排序***********/
void QuickSort(int r[],int low,int high)
{
int i;
if (low < high)
{
int pivotpos = Partition(r, low, high);
QuickSort(r, low, pivotpos-1);
QuickSort(r, pivotpos + 1, high);
}
}
void Print(int r[])
{
printf("\n快速排序后序列为:");
for (int i = 0; i < count; i++)
printf("%d ", r[i]);
}
//快速排序的划分操作版本
int Partition(int r[],int low,int high)
{
int pivot = r[low]; //将当前表中第一个元素设为基准,对表进行划分
while (low < high)
{
while (low < high && r[high] >= pivot)
--high;
r[low] = r[high];//将比基准小的元素移到左端
while (low < high && r[low] <= pivot)
++low;
r[high] = r[low]; //将比基准大的元素移动到右端
}
r[low] = pivot; //基准元素存放到最终位置
return low; //返回存放基准值的最终位置
}
void main()
{
Indata();
BubbleSort(R, count);
QuickSort(R, 0, count-1);
Print(R);
system("pause");
}
结果图