c语言入门问题,求解答
发布网友
发布时间:2023-05-26 03:25
我来回答
共2个回答
热心网友
时间:2024-05-18 17:47
bool cmp(const int &a,const int &b)
{
if(a > b)return false;
else return true;
}
template<class T>
void Swap(T &t1,T &t2)
{
T tmp;
tmp = t1,t1 = t2,t2=tmp;
}
void bubblesort(int arr[],int n)
{
int i,j;
bool flag = false;
if(NULL == arr || n <= 0)return;
for(i = 0;i < n - 1;i ++)
{
flag = false;
for(j = 0;j < n - 1 - i;j ++)
{
if(cmp(arr[j],arr[j+1]))
{
Swap(arr[j],arr[j+1]);
flag = true;
}
}
if(!flag)
{
break;
}
}
}
void insertsort(int arr[],int n)
{
int i,j;
int insert;
if(arr == NULL || n <= 0)return;
for(i = 1;i <= n;i ++)
{
insert = arr[i];
arr[0] = arr[i];
for(j = i;cmp(arr[j-1],insert);j --)
{
arr[j] = arr[j-1];
}
arr[j] = insert;
}
}
void selectsort(int arr[],int n)
{
int i,j;
for(i = 0;i < n;i ++)
{
int maxindex = 0;
for(j = 0;j < n - i;j ++)
{
if(arr[maxindex] < arr[j])
{
maxindex = j;
}
}
Swap(arr[maxindex],arr[n-1-i]);
}
}
int partition(int arr[],int s,int e)
{
int pov = arr[s];
if(arr == NULL || s > e)return -1;
else
{
while(s < e)
{
while(s < e && cmp(arr[e],pov)) e--;
arr[s] = arr[e];
while(s < e && cmp(pov,arr[s])) s++;
arr[e] = arr[s];
}
arr[s] = pov;
return s;
}
}
void Qsort(int arr[],int s,int e)
{
if(arr == NULL || s > e)return;
int pov = partition(arr,s,e);
Qsort(arr,s,pov - 1);
Qsort(arr,pov + 1,e);
}
int main()
{
int arr[] = {-1,9,5,1,2,3,4,8,77,6,88,100,-8,11,12,13,10,89,5689,-9,777,999};
typedef int sizet;
sizet size = 21;
int algorithm = 3;
switch(algorithm)
{
case 0:
bubblesort(arr,size);
break;
case 1:
insertsort(arr,size);
break;
case 2:
selectsort(arr,size+1);
break;
case 3:
Qsort(arr,0,size);
break;
}
for(int i = 0;i <= size;i ++)
if(i < size)cout << arr[i] << " , ";
else cout << arr[i] << endl;
return 0;
}
根据修改cmp函数可以实现升序和降序
热心网友
时间:2024-05-18 17:47
说的具体点,你想实现什么