专注电子技术学习与研究
当前位置:单片机教程网 >> MCU设计实例 >> 浏览文章

用VC++类实现快速排序(并输出过程)

作者:佚名   来源:本站原创   点击数:  更新时间:2013年12月01日   【字体:



&&&&&&&&&&&&&&&&&&&&&&&&&&&&主函数&&&&&&&&&&&&&&&&&&&&&&
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include "WangQi.h"
using namespace std;
#define MAX 100
void main(){
SeqList L;
int num;
cout<<"请输入要排序的元素个数:"<<endl;
cin>>num;
cout<<"请输入要排序的元素:"<<endl;
for(int i=1;i<=num;i++)
cin>>L.r[i];
L.length=num;
//输出排序前的顺序表
L.output(&L,1,L.length,-1);
L.quicksort(&L,1,L.length);
L.output(&L,1,L.length,-2);
}
&&&&&&&&&&&&&&&&&&&含有类定义的头文件&&&&&&&&&&&&&&&&&&&&&&&&&
#include <iostream>
using namespace std;
#define MAX 100
class SeqList{
public:
int r[MAX+1];
int length;

void output(SeqList *L,int low, int high,int pivotloc){
int i;

if(pivotloc==-1||pivotloc==-2){
  if(pivotloc==-1)
       cout<<"初始状态:{"<<'\t';
  else cout<<"排序结果:{"<<'\t';
     for(i=low;i<=high;i++)
      cout<<L->r[i]<<'\t';
      cout<<"}";
      }else {
     cout<<"划分结果:{"<<'\t';
   for(i=low;i<pivotloc;i++)
      cout<<L->r[i]<<'\t';
      cout<<"}"<<L->r[pivotloc]<<"{";
    for(i=pivotloc+1;i<=high;i++)
     cout<<L->r[i]<<'\t';
    cout<<"}";
 }
  cout<<'\n'<<endl;
}


int partition(SeqList *L,int low,int high){
  int pivotkey;
  int temp1=low,temp2=high;
  L->r[0]=L->r[low];
  pivotkey=L->r[low];
  while (low<high){
     while (low<high && L->r[high]>=pivotkey)
     --high;
     L->r[low]=L->r[high];
    while(low<high && L->r[low]<=pivotkey)
    ++low;
    L->r[high]=L->r[low];
   }
    L->r[low]=L->r[0];
    output(L,temp1,temp2,low);
    return low;
    }


void quicksort(SeqList *L,int low,int high){
int pivotloc;
   if(low<high)
     pivotloc=partition(L,low,high);
    if(low<pivotloc-1)
     quicksort(L,low,pivotloc-1);
    if(high>pivotloc+1)
     quicksort(L,pivotloc+1,high);
}
};


 

关闭窗口

相关文章