#include <stdio.h>
#include <stdlib.h> //rand()
#include <malloc.h>
#include <algorithm>
using namespace std;
//自定义降序函数
//template<typename T>
bool compare(int x,int y)
{
return x > y;
}
/*
样例输入:
4
1 4 3 2
10
1 9 8 5 6 3 4 2 0 7
29
8,31,60,33,17,4,51,57,49,35,
11,43,37,3,13,52,6,19,25,32,
54,16,5,41,7,23,22,46,29
样例输出:
1 2 3 4
0 1 2 3 4 5 6 7 8 9
总结:
华中科技大,满分10分:得分8分
一定要严格按照输入输出要求来
关键:
1 int scanf(const char* fromat[,argument]....):返回0表示没有被赋值
2 return (rand()%(max - min + 1) + min);//牛逼,用除以这个范围内的数,加上min来得到min~max之间任意数
*/
void baseSort(int *A,int n)
{
int i;
for(i = 0 ; i < n; i++)
{
//判断当前趟是否需要排序的标记,为true表示不需要排序
bool flag = true;
for(int j = n-1;j > i; j--)
{
//后面的比前面的小,才交换
if(A[j] < A[j-1])
{
int temp = A[j];
A[j] = A[j-1];
A[j-1] = temp;
flag = false;
}
}
if(flag==true)
{
break;
}
}
//输出
/*
for(i = 0;i < n; i++)
{
printf("%d ",*(A+i));
}
*/
}
//快速排序,实际上递归,忘记了,忘记了,快速排序是同时需要下标和上标的
/*
void quickSort(int* A,int n)
{
int iPos = partition(0,n-1,A);
if()
{
partition(iPos,n-1,A);
partition(0,iPos-1,A);
quickSort();
}
}
*/
int randomInRange(int min,int max)
{
return (rand()%(max - min + 1) + min);//牛逼,用除以这个范围内的数,加上min来得到min~max之间任意数
}
void swap(int* p1,int* p2)
{
int iTemp = *p1;
*p1 = *p2;
*p2 = iTemp;
}
int partition(int *A,int low,int high)
{
//printf("Enter partition\n");
int iIndex = randomInRange(low,high);
//int iPos = A[iIndex];
swap(&A[low],&A[iIndex]);//交换第一个数与枢轴
int iPos = A[low];
while(low<high)//注意low<high,low=high会死循环
{
//后面>枢轴,则一直递减高位的指标
//while(A[high]>iPos)//漏了low<high的判断条件,否则一直死循环
while(low<high&&A[high]>= iPos)
{
high--;
}
//printf("high:%d\n",high);
//后面<=枢轴,高位的数与低位的数进行交换
A[low] = A[high];
//while(A[low]<iPos)
while(low<high&&A[low]<= iPos)
{
low++;
}
//printf("low:%d\n",low);
A[high] = A[low];
}
A[low] = iPos;//易错,不能忘记对枢轴位置的元素进行正确赋值,随机选枢轴这步应该不需要了
//printf("Hello %d",low);//没走到这一步
return low;//返回当前这一趟排序的枢轴位置
}
void quickSort(int *A,int low,int high)
{
if(low<high)//注意low<high,low<=high,死循环
{
//printf("Enter quickSort\n");
int iPos = partition(A,low,high);//0
quickSort(A,low,iPos-1);//0,0
quickSort(A,iPos+1,high);
}
// return;
}
void print(int* A,int n)
{
for(int i = 0; i < n;i++)
{
printf("%d ",A[i]);
}
}
int main(int argc,char* argv[])
{
//printf("Please input the total number you want to sort:");
int iNum;
//while(0!=scanf("%d",&iNum))
//若为输入字符串用,while(gets())
while(EOF!=scanf("%d",&iNum))//因为存在多组数据,必须用EOF!=scanf("%d",&iNum)用于循环输入,EOF表示在读一个字符时遇到错误或者文件末尾符号,或者字符串末尾
{
//printf("please input these numbers:\n");
int *iArr = (int*)malloc(iNum*sizeof(int));
for(int i = 0; i < iNum;i++)
{
int iValue;
scanf("%d",&iValue);
iArr[i] = iValue;
}
//printf("\nThe sort result are as follows:\n");
//baseSort(iArr,iNum);
quickSort(iArr,0,iNum-1);
//sort(iArr,iArr+iNum);
//使用降序排序
//sort(iArr,iArr+iNum,compare);
print(iArr,iNum);
printf("\n");
free(iArr);
}
getchar();
return 0;
}
机试算法讲解:第1题 冒泡排序与快速排序
最新推荐文章于 2021-04-08 12:32:09 发布