排序算法练习二

今天依旧是排序算法。做了两个练习,一个快速排序,一个简单选择排序。后面看了堆排序和归并排序,理解了编程思路。

还是昨天的经验,要一步一步仔细分析,想清楚每一步执行的结果,整合思路,顺清楚逻辑,嗯,重要的是思路。

快速排序:

关键思想:分成左右两部分,左右分别排序,通过比较两个整数是否相等判断本次是否比较完了。

#include<iostream>
using std::cout;
using std::endl;
int sortone(int a[],int first,int end)
{
int i,j,temp;
i=first;j=end;
while(i<j)
{ while(i<j&&a[i]<a[j]) j--;//i<j to insure the order
if(i<j) //the same as former 
{temp=a[i]; a[i]=a[j];a[j]=temp;
i++;
cout<<"left"<<endl;
}
while(i<j&&a[i]<a[j]) i++;
if(i<j)                 //the same as former
                {temp=a[i]; a[i]=a[j];a[j]=temp;
                j--; //change to the other side
                cout<<"right"<<endl;
}
}
cout<<"i="<<i<<endl;
for(int t=0;t<7;t++)
        cout<<a[t]<<"  ";
        cout<<endl;
return i;   //to record the position
}


void fastsort(int a[],int first,int end)
{ int pivot;
if(first<end)
{pivot=sortone(a,first,end);//the first time to select the middle position 
fastsort(a,first,pivot-1);//the left part
fastsort(a,pivot+1,end);//the right part
}
}
int main()
{int r[]={23,13,49,6,31,19,28};
fastsort(r,0,6);
for(int i=0;i<7;i++)
cout<<r[i]<<"  ";
cout<<endl;
return 0;
}

简单选择排序:

关键思想:从所有待排序中选出最小的放在最前面,每次选择最小的放在最前面,后面是未排序的,一个整数标志着未排序的最前面那个,每次从这个开始。

#include<iostream>
using std::cout;
using std::endl;


void selectsort(int a[],int n)
{
int i(0),j,temp,index;

while(i<n)
{index=i;
for(j=i+1;j<n;j++)
if(a[j]<a[index])index=j;//to record the smallest number
if(index!=i)//put the smallest to the sorted part
{ temp=a[i];
a[i]=a[index];
a[index]=temp;
}
i++;
cout<<i<<"  ";
for(int t=0;t<7;t++)
        cout<<a[t]<<"  ";
        cout<<endl;
}
}


int main()
{ int r[]={49,27,65,97,76,13,38};
selectsort(r,7);
for(int t=0;t<7;t++)
cout<<r[t]<<"  ";
cout<<endl;
return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值