排序 选择问题 Partition函数

来源:互联网 发布:godaddy创建数据库 编辑:程序博客网 时间:2024/05/18 12:02

0508选择问题

完善了一下书上的伪代码  虽然能用 但是不是很理解Partition函数

// 0508选择问题.cpp : Defines the entry point for the console application.//#include "stdafx.h"#include <iostream>using namespace std;int Partition (int r[],int low, int high)    //划分 low和high为数组的索引{int i=low,j=high;                     //初始化待划分区间while(i<j){while(i<j && r[i]<=r[j])           //右侧扫描j--;if(i<j){int temp=r[i];                //将较小记录交换到前面r[i]=r[j];r[j]=temp;i++;}while(i<j && r[i] <= r[j])          //左侧扫描i++;if(i<j){int temp=r[i];               //将较大记录交换到后面r[i]=r[j];r[j]=temp;j--;}}return i;                 //返回轴值记录}//这里不是很理解左侧扫描和右侧扫描 有懂的人能给我讲下会非常感谢!int SelectMink(int r[],int low,int high,int k){int s;s=Partition(r,low,high);if(s==k)return r[s];if(s>k)return SelectMink(r,low,s-1,k);if(s<k)return SelectMink(r,s+1,high,k);}void main(){int r[5];cout<<"输入数列:"<<endl;for(int i=0; i<5; i++){int a;cin>>a;r[i]=a;}int low;cout<<"输入low high:"<<endl;cin>>low;int high;cin>>high;int k;cout<<"输入k:";cin>>k;k=k-1;cout<<endl;Partition(r,low,high);cout<<SelectMink(r,low,high,k)<<endl;}

舍伍德型概率算法——快速算法

在Partition函数的基础上加上了随机数发生器,按照书上说的应该是会消除不同输入实例对算法时间性能的影响

/ 0520.cpp : Defines the entry point for the console application.//#include "stdafx.h"#include <iostream>#include<stdlib.h>using namespace std;int Random(int a,int b){return (rand()%(b-a)+a);}int Partition (int r[],int low, int high)    //划分 low和high为数组的索引  {      int i=low,j=high;                     //初始化待划分区间      while(i<j)      {          while(i<j && r[i]<=r[j])           //右侧扫描              j--;            if(i<j)          {              int temp=r[i];                //将较小记录交换到前面              r[i]=r[j];              r[j]=temp;              i++;          }            while(i<j && r[i] <= r[j])          //左侧扫描              i++;            if(i<j)          {              int temp=r[i];               //将较大记录交换到后面              r[i]=r[j];              r[j]=temp;              j--;          }         }        return i;                 //返回轴值记录  } void RandQuickSort(int r[],int low,int high){int i,k,temp;if(low<high){i=Random(low,high);temp=r[low];r[low]=r[i];r[i]=temp;k=Partition(r,low,high);RandQuickSort(r,low,k-1);RandQuickSort(r,k+1,high);}}int main(int argc, char* argv[]){int r[5];      cout<<"输入数列:"<<endl;      for(int i=0; i<5; i++)      {          int a;          cin>>a;          r[i]=a;      }        int low;      cout<<"输入low high:"<<endl;      cin>>low;      int high;      cin>>high;            cout<<endl;      RandQuickSort(r,low,high);  for( i=0; i<5; i++)      {          cout<<r[i]<<endl;     } return 0;}


1 0