课时16作业
Description
读取10个整型数据12 63 58 95 41 35 65 0 38 44,然后通过冒泡排序,快速排序,插入排序,分别对该组数据进行排序,输出3次有序结果,每个数的输出占3个空格
Input
12 63 58 95 41 35 65 0 38 44
Output
输出3次有序结果
0 12 35 38 41 44 58 63 65 95
0 12 35 38 41 44 58 63 65 95
0 12 35 38 41 44 58 63 65 95
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
typedef int ElemType;
typedef struct {
ElemType *elem;
int TableLen;
}SSTable;
void ST_Init(SSTable &ST,ElemType len)
{
ST.TableLen=len;//申请10个元素空间
ST.elem=(ElemType*) malloc(sizeof (ElemType)*ST.TableLen);
srand(time(NULL));
for (int i = 0; i < ST.TableLen; ++i) {
ST.elem[i]=rand()%100;//随机10个数
}
}
void ST_Print(SSTable ST)
{
for (int i = 0; i < ST.TableLen; ++i) {
printf("%3d",ST.elem[i]);
}
printf("\n");
}
//交换两个元素
void swap(ElemType &a,ElemType &b)
{
ElemType temp;
temp=a;
a=b;
b=temp;
}
void InsertSort(ElemType *A,int len)
{
int i,j,insertVal;
for ( i = 1; i < len; ++i) //控制要插入的数
{
insertVal=A[i];//先保存要插入的数值
//内层控制比较,j要大于等于0,同时A[j]大于insertVal,A[j]位置元素往后覆盖
for(j=i-1;j>=0&&A[j]>insertVal;j--)
{
A[j+1]=A[j];
}
A[j+1]=insertVal;
}
}
//冒泡排序
void BubbleSort(ElemType A[],int n)
{
bool flag;
for (int i = 0; i < n-1; ++i) //这里可以推出i最多可以访问到8
{
flag= false;//元素是否发生交换的标志
for (int j = n-1; j > i;j--)//把最小值就放在最前面
{
if(A[j-1]>A[j])
{
swap(A[j-1],A[j]);
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];//把比分隔值小的那个元素,放到A[low]
while (low < high && A[low]<=pivot)//从前往后遍历,找到一个比分隔值大的
low++;
A[high]=A[low];//把比分割值大的那个元素,放到A[high],因为刚才high位置的元素已经放到low位置
}
A[low]=pivot;
return low;//返回分隔值所在的下标
}
//递归实现
void QuickSort(ElemType A[],int low,int high)
{
if(low < high)
{
int pivotpos=Partition(A,low,high);//分割点左边的元素都比分割点要小,右边的比分割点大
QuickSort(A,low,pivotpos-1);
QuickSort(A,pivotpos+1,high);
}
}
int main() {
SSTable ST;
ST.TableLen=10;
ST.elem=(ElemType*) malloc(sizeof (ElemType)*ST.TableLen);
for (int i = 0; i < ST.TableLen; ++i) {
scanf("%d",&ST.elem[i]);
}
BubbleSort(ST.elem,10);
ST_Print(ST);
QuickSort(ST.elem,0,9);//注意这个位置是n-1,也就是9,因为函数里取了high位置的值
ST_Print(ST);
InsertSort(ST.elem,10);
ST_Print(ST);
return 0;
}