快速排序法

來源:互聯網
上載者:User

標籤:key   main   排序   style   遞迴   i++   應該   均值   個數   

    1. #include <stdio.h>
    2. #include <stdlib.h> 
    3.  
    4. void swap(int *x,int *y)  //  交換函數
    5. {
    6.    int temp;
    7.    temp = *x;
    8.    *x = *y;
    9.    *y = temp;
    10. }
    11.  
    12. int choose_pivot(int i,int j )   //取兩數平均值函數
    13. {
    14.    return((i+j) /2);
    15. }
    16.  
    17. void quicksort(int list[],int m,int n)   //快速排序函數,m,n分別是左界 右界  比如10個數排序中的 0 和9
    18. {
    19.    int key,i,j,k;
    20.    if( m < n)
    21.    {
    22.       k = choose_pivot(m,n);    求得中間位置的值  
    23.       swap(&list[m],&list[k]);
    24.       key = list[m];
    25.       i = m+1;
    26.       j = n;
    27.       while(i <= j)
    28.       {
    29.          while((i <= n) && (list[i] <= key))
    30.                 i++;
    31.          while((j >= m) && (list[j] > key))
    32.                 j--;
    33.          if( i < j)
    34.                 swap(&list[i],&list[j]);
    35.       }
    36.      // 交換兩個元素的位置
    37.       swap(&list[m],&list[j]);
    38.      // 遞迴地對較小的資料序列進行排序
    39.       quicksort(list,m,j-1);
    40.       quicksort(list,j+1,n);
    41.    }
    42. }
    43.  
    44. void printlist(int list[],int n)
    45. {
    46.    int i;
    47.    for(i=0;i<n;i++)
    48.       printf("%d\t",list[i]);
    49. }
    50.  
    51. void main()
    52. {
    53.    const int MAX_ELEMENTS = 10;
    54.    int list[MAX_ELEMENTS];
    55.  
    56.    int i = 0;
    57.    
    58.    // 產生以數列填滿的隨機數
    59.    for(i = 0; i < MAX_ELEMENTS; i++ ){
    60.      list[i] = rand();
    61.    }
    62.    printf("進行排序之前的序列:\n");
    63.    printlist(list,MAX_ELEMENTS);
    64.    
    65.    // sort the list using quicksort
    66.    quicksort(list,0,MAX_ELEMENTS-1);
    67.  
    68.    // print the result
    69.    printf("使用快速排序演算法進行排序之後的序列:\n");
    70.    printlist(list,MAX_ELEMENTS);
    71. }
  1. 這段程式並不難,應該很好看懂,我把過程大致講一下,首先你的腦子裡先浮現一個數組和三個指標,第一個指標稱為p指標,在整個過程結束之前它牢牢的指向第一個數,第二個指標和第三個指標分別為lo指標和hi指標,分別指向最左邊的值和最右邊的值。lo指標和hi指標從兩邊同時向中間逼近,在逼近的過程中不停的與p指標的值比較,如果lo指標的值比p指標的值小,lo++,還小還++,再小再++,直到碰到一個大於p指標的值,這時視線轉移到hi指標,如果 hi指標的值比p指標的值大,hi--,還大還--,再大再--,直到碰到一個小於p指標的值。這時就把lo指標的值和hi指標的值做一個調換。持續這過程直到兩個指標碰面,這時把p指標的值和碰面的值做一個調換,然後返回p指標新的位置。

快速排序法

聯繫我們

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