好,細部分解完快速排序之後,讓我們依照由左到右、由小到大的順序,再玩一次快速排序。

這一次,我們要用最簡短的方式試看看

 

 

#include <iostream>
#include<stdlib.h>
#include<time.h>
using namespace std;

#define S(a,b){int temp=a; a=b; b=temp;}
const int size = 10;

void print(int a[], int size)
{
    for(int i=0;i<size;i++)
    {
        cout<<a[i]<<"\t";
    }
}

void QS(int a[], int L, int R)
{
    if(L<R)
    {
        int i=L;
        int j=size;
        while(true)
        {
            while(i+1<size && a[++i]<a[L]);//如果 i 的下一個超出邊界,或者是 i 本身的值大於L的值,跳出迴圈
            while(j-1>(-1) && a[--j]>a[L]);//如果 j 的下一個超出邊界,或者是 j 本身的值小於L的值,跳出迴圈
            if(i>=j){break;}
            S(a[i],a[j]);//這裡其實加個else應該會更清楚
        }
        S(a[L],a[j]);//如果 i 位置已經超過 j 位置,那 l 的值與 j 的值互換
        QS(a,L,j-1);
        QS(a,j+1,R);
    }
}

void main()
{
    srand(time(NULL));
    int arr[size]={0};
    for(int i=0; i<size;i++)
    { arr[i]=rand()%(100)+1;}
    QS(arr,0,size-1);
    print(arr,size);
    system("pause");
}

 

為什麼我會研究這麼久@@?

文章標籤
快速排序 quick sort
全站熱搜
創作者介紹
創作者 archerdevil 的頭像
archerdevil

Archer, who doesn't know how to shoot...

archerdevil 發表在 痞客邦 留言(1) 人氣()