#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>
//读取10个整型数据12 63 58 95 41 35 65 0 38 44,然后通过冒泡排序,快速排序,插入排序,分别对该组数据进行排序,
// 输出3次有序结果,每个数的输出占3个空格
typedef int ElemType;
typedef struct{
ElemType *elem;//存储元素的起始地址
int TableLen;//元素个数
}SSTable;
//随机数生成
void ST_Init(SSTable &ST,int len)
{
ST.TableLen=len;
ST.elem=(ElemType *) malloc(sizeof (ElemType)*ST.TableLen);//申请空间,当数组使用
int i;
srand(time(NULL));//随机数生成,随机生成10元素
for(i=0;i<ST.TableLen;i++)
{
ST.elem[i]=rand()%100;//生成的是0-99之间
}
}
//打印元素
void ST_print(SSTable ST)
{
for (int i = 0; i < ST.TableLen; i++)
{
printf("%3d",ST.elem[i]);
}
printf("\n");
}
//交换两个位置值
void swap(int &a,int &b)
{
int t;
t=a;
a=b;
b=t;
}
//冒泡排序
void BubbleSort(ElemType *A,int n)
{
int i,j;
bool flag;
for(i=0;i<n-1;i++)//i最多访问到 8
{
flag= false;
for(j=n-1;j>i;j--)
{
if(A[j]<A[j-1])//从小到大排序
{
swap(A[j],A[j-1]);
flag= true;
}
}
if(false==flag)//如果一趟比较没有发生任何交换,说明有序,提前结束排序
return;
}
}
//快排核心
int Partition(ElemType *A,int low,int high)
{
ElemType pivot=A[low];
while (low<high)
{
while (low<high&&A[high]>=pivot)
high--;
A[low]=A[high];
while (low<high&&A[low]<=pivot)
low++;
A[high]=A[low];
}
A[low]=pivot;
return low;
}
//快速排序
void QuickSort(ElemType *A,int low,int high)
{
if(low<high)
{
int pivot_pos=Partition(A,low,high);//分割点左边的元素都比分割点要小,右边的比分割点大
QuickSort(A,low,pivot_pos-1);
QuickSort(A,pivot_pos+1,high);
}
}
//插入排序
void InsertSort(ElemType *A,int n)
{
int i,j,insertVal;
for(i=1;i<n;i++)//每次要插入的值
{
insertVal=A[i];//赋值每次要插入的值
for(j=i-1;j>=0&&A[j]>insertVal;j--)
{
A[j+1]=A[j];
}
A[j+1]=insertVal;
}
}
int main() {
SSTable ST;
ST_Init(ST,10);//申请 10 个元素空间
ElemType A[10]={ 12,63,58,95,41,35,65,0,38,44};//内存 copy 接口,当你 copy 整型数组,或者浮点型时,要用 memcpy,不能用 strcpy,初试考 memcpy概率很低
memcpy(ST.elem,A,sizeof(A));//这是为了降低调试难度,每次数组数据固定而设计的ST_print(ST);
ElemType B[10];
for (int i = 0; i <10 ; ++i) {
scanf("%d",&A[i]);
}
// ST_print(ST);//排序前打印
//冒泡排序
BubbleSort(ST.elem,10);
ST_print(ST);//排序后打印
//快速排序
memcpy(ST.elem,A,sizeof(A));//重新赋值进行测试
QuickSort(ST.elem,0,9);
ST_print(ST);//排序后打印
//插入排序
memcpy(ST.elem,A,sizeof(A));//重新赋值进行测试
InsertSort(ST.elem,10);
ST_print(ST);//排序后再次打印
return 0;
}
王道c语言督学营课时16作业
最新推荐文章于 2024-05-06 23:46:33 发布