排序算法练习二

来源:互联网 发布:javascript 模块化编程 编辑:程序博客网 时间:2024/05/16 10:55

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

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

快速排序:

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

#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;
}

原创粉丝点击