排序算法练习二
来源:互联网 发布: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;
}
- 排序算法练习二
- 算法练习二 堆排序
- 排序算法自我练习(二)——选择排序
- [算法练习] 冒泡排序
- 内部排序算法练习
- 排序算法练习
- 【算法练习】数组排序
- 基础排序算法练习
- 算法练习-归并排序
- 算法练习-快速排序
- 排序算法练习-二分法
- 算法练习---冒泡排序
- 排序算法练习
- 经典排序算法练习
- 算法练习(二)
- 算法练习一 合并排序
- 练习4______排序算法
- 简单算法练习--插入排序
- 【转】sk_buff详解
- .NET多线程编程(1):多任务和多线程
- hdu 4442 Physical Examination
- Symfony
- .NET多线程编程(2):System.Threading.Thread类
- 排序算法练习二
- 支持向量机(SVM)基础
- u盘被写保护怎么办
- 一个java时钟 非常精致!
- 【转载】网络协议学习方法和工具
- android应用实现自动检测版本升级
- mysql负载均衡 方案
- C# Base64加密解密算法实现
- 线程中的参数传递