快速排序的C語言代碼實現

來源:互聯網
上載者:User

作者:李慧芹,華清遠見嵌入式學院講師。

快速排序實質上是對“冒泡排序”的一種改進,整個排序過程可概括為:通過N趟的排序將原本的排序資料分為若干塊進行分塊排序,而在每趟排序過程中,以指定的關鍵字將待排資料分別分為比關鍵字大的部分和比關鍵字小的部分,反覆上述過程,將整個待排數列分散為若干個小數列而分別進行排序操作。假設我們現對一列數進行快速排序,其C語言代碼實現如下:

#include <stdio.h>
        int partition(int *data,int low,int high)
        {       int t = 0;
                t = data[low];
                while(low < high)
                {       while(low < high && data[high] >= t)
                                high--;
                        data[low] = data[high];
                        while(low < high && data[low] <= t)
                                low++;
                        data[high] = data[low];
                }
                data[low] = t;
                return low;
        }

void sort(int *data,int low,int high)        //快排每趟進行時的樞軸要重新確定,由此進 //一步確定每個待排小記錄的low及high的值
        {       if(low >= high)
                        return ;
                int pivotloc = 0;
                pivotloc = partition(data,low,high);
                sort(data,low,pivotloc-1);
                sort(data,pivotloc+1,high);
        }
        void quick_sort(int *data,int n)         //該函數進行sort過程的調用
        {         sort(data,0,n-1); }

int main()
        {       int i;
                int data[]={49,38,32,98,65,74,12,8};
                quick_sort(data,sizeof(data)/sizeof(int));
                for( i = 0 ; i < sizeof(data)/sizeof(int); i++)
                printf("%d ",data[i]);
                printf("/n");
                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.