專(zhuān)注電子技術(shù)學(xué)習(xí)與研究
當(dāng)前位置:單片機(jī)教程網(wǎng) >> MCU設(shè)計(jì)實(shí)例 >> 瀏覽文章

用VC++類(lèi)實(shí)現(xiàn)快速排序(并輸出過(guò)程)

作者:佚名   來(lái)源:本站原創(chuàng)   點(diǎn)擊數(shù):  更新時(shí)間:2013年12月01日   【字體:



&&&&&&&&&&&&&&&&&&&&&&&&&&&&主函數(shù)&&&&&&&&&&&&&&&&&&&&&&
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include "WangQi.h"
using namespace std;
#define MAX 100
void main(){
SeqList L;
int num;
cout<<"請(qǐng)輸入要排序的元素個(gè)數(shù):"<<endl;
cin>>num;
cout<<"請(qǐng)輸入要排序的元素:"<<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);
}
&&&&&&&&&&&&&&&&&&&含有類(lèi)定義的頭文件&&&&&&&&&&&&&&&&&&&&&&&&&
#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ài):{"<<'\t';
  else cout<<"排序結(jié)果:{"<<'\t';
     for(i=low;i<=high;i++)
      cout<<L->r[i]<<'\t';
      cout<<"}";
      }else {
     cout<<"劃分結(jié)果:{"<<'\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);
}
};


 

關(guān)閉窗口

相關(guān)文章