處理海量資料的三大排序之——快速排序(C++)

來源:互聯網
上載者:User

標籤:style   blog   color   os   io   strong   資料   for   

 

代碼實現                                                                                                                                                                                                       

#include "stdafx.h"#include <iostream>#include <ctime>using namespace std;int a[1000000];int tempA[1000000];#define BEGIN_RECORD \{                                clock_t ____temp_begin_time___;    ____temp_begin_time___=clock();#define END_RECORD(dtime) \dtime=float(clock()-____temp_begin_time___)/CLOCKS_PER_SEC;}/* 快速排序(挖坑填數) a - 待排序的數組 l - 排序地區的左邊界     r - 排序地區的右邊界*/void quickSort(int a[], int l, int r){    if(l < r)    //快排每次把一個數排到正確位置,便以此點把原排序地區細分為兩個更小的排序地區。通過不斷遞迴,當新的排序地區右邊界不再大於左邊界時,說明已不需要排序,則停止遞迴,排序完畢    {        int i,j,x;        i = l;        j = r;        x = a[i];    //選取排序地區左邊第一個數作為本次排序的數        while(i < j)    //該迴圈可稱之為換坑過程,i,j相當於左右兩邊坑的位置,當右邊坑位置不再大於左邊坑位置時(此時兩坑位置必定相同),說明已比較到中點,結束換坑過程        {                        while(i < j && x < a[j])    //從右向左找小於x的值            {                j--;            }            if(i < j)                    //找過後就將其換到左邊第1個位置,下一次則填入左邊第2個位置,以此類推            {                a[i++] = a[j];            }            while(i < j && x > a[i])    //從左向右找大於x的值            {                i++;            }            if(i < j)                    //找到後將其填入右邊第1個位置,下一次則填入右邊第2個位置,以此類推            {                a[j--] = a[i];            }        }        a[i] = x;    //當換坑過程結束後,在i位置以左的值都小於x,i位置以右的值都大於x,說明x找到了正確的位置,將x值填入(填坑過程)        //將x值位置以左,以右分為兩個新的排序地區,重複換坑填坑的過程        quickSort(a, l, i-1);        quickSort(a, i+1, r);    }}void printArray(int a[], int length){    cout << "數組內容:";    for(int i = 0; i < length; i++)    {        if(i == 0)            cout << a[i];        else            cout << "," << a[i]; }    cout << endl;}int _tmain(int argc, _TCHAR* argv[]){    float tim; for (int i = 0; i < 1000000; i++)    {        a[i] = int(rand() % 100000);    }    BEGIN_RECORD //printArray(a, sizeof(a)/sizeof(int));    quickSort(a, 0, sizeof(a)/sizeof(int) - 1);    //printArray(a, sizeof(a)/sizeof(int));    END_RECORD(tim)        cout << "已耗用時間:" << tim << "s" <<  endl; system("pause");    return 0;}

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.