C語言實現快速排序法(分治法)

來源:互聯網
上載者:User

標籤:title   inter   ide   倒數   解決辦法   dex   string   快速   div   

title: 快速排序法(quick sort)
tags: 分治法(divide and conquer method)
grammar_cjkRuby: true
---

演算法原理

分治法的基本思想:將原問題分解為若干個更小的與原問題相似的問題,然後遞迴解決各個子問題,最後再將各個子問題的解組合成原問題的解。
利用分治法可以將解決辦法分為 “三步走” 戰略:
(1) 在資料集中選定一個元素作為“基準”(pivot)
(2) 將所有資料集小於基準的元素放在基準左邊,大於基準的元素放在基準右邊,把原資料集分為兩個資料集的操作叫做“分區”,分區結束後基準所在的位置也就是基準最後的位置
(3) 分別對基準左右兩邊的資料集進行前兩個步驟,直至資料集只剩下一個資料為止

C語言實現
/***********************///章節:第四章//內容:快速排序/***********************/#include<stdio.h>#include<string.h>#include<stdlib.h>#include<sys/stat.h>void fastsort(int v[], int first, int last); int main(){    int i, v[10] = {1,243,43,5,6,634,434,23,12,7};    fastsort( v, 0, 9);    for(i = 0; i < 10; i++)        printf("%d  ",v[i]);    return 0;}void fastsort(int v[], int first, int last){    int i, storeindex;    void swap(int v[], int i, int j);    if(first >= last)        return;  //fewer than two ele    swap(v, last, (first + last)/2); //move partition elem    storeindex =  first;    for(i = first; i <= last-1; i++)        if(v[i] <= v[last])            {                swap(v, storeindex, i);                storeindex += 1;            }    swap(v, last, storeindex);    fastsort(v, first, storeindex - 1);    fastsort(v, storeindex + 1, last);}/*swap:interchange v[i] and v[j]*/void swap(int v[], int i, int j){    int temp;    temp = v[j];    v[j] = v[i];    v[i] = temp;}
執行個體分析

(1)取5作為pivot,然後將其移動到最後一個位置
(2)從第一個數3到倒數第二個數5分別和pivot比較,如果小於等於pivot的數依次從前向後排
(4)將pivot 5移回兩個分區中間

C語言實現快速排序法(分治法)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.