Chinaunix首页 | 论坛 | 博客
  • 博客访问: 99032
  • 博文数量: 20
  • 博客积分: 648
  • 博客等级: 上士
  • 技术积分: 222
  • 用 户 组: 普通用户
  • 注册时间: 2010-10-02 11:43
文章分类

全部博文(20)

文章存档

2013年(3)

2012年(8)

2011年(7)

2010年(2)

我的朋友

分类: C/C++

2011-03-25 16:09:25

快速排序:
快速排序操作如下,将数组a[r..p]分成两个子数组,a[p..q], a[q+1,r],并且保证a[p..q]中的每一个值小于a[q+1,r]。然后再对每个子数组做相同的操作。

伪码:
Normal 0 7.8 磅 0 2 false false false EN-US ZH-CN X-NONE MicrosoftInternetExplorer4 /* Style Definitions */ table.MsoNormalTable {mso-style-name:普通表格; mso-tstyle-rowband-size:0; mso-tstyle-colband-size:0; mso-style-noshow:yes; mso-style-priority:99; mso-style-qformat:yes; mso-style-parent:""; mso-padding-alt:0cm 5.4pt 0cm 5.4pt; mso-para-margin:0cm; mso-para-margin-bottom:.0001pt; mso-pagination:widow-orphan; font-size:10.5pt; mso-bidi-font-size:11.0pt; font-family:"Calibri","sans-serif"; mso-ascii-font-family:Calibri; mso-ascii-theme-font:minor-latin; mso-hansi-font-family:Calibri; mso-hansi-theme-font:minor-latin; mso-font-kerning:1.0pt;}

QuickSort

1.        If p < r then

a)        q Partition (A, p, r)

b)        Recursive call to Quick Sort (A, p, q)

c)         Recursive call to Quick Sort (A, q + r, r)

 

PARTITION (A, p, r)

1.        x A[p]

2.        i p-1

3.        j r+1

4.        while TRUE do

a)        Repeat j j-1

b)        until A[j] x

c)        Repeat i i+1

d)        until A[i] x

e)        if i < j

f)         then exchange A[i] A[j]

g)        else return j

 


  1. void quickSort(int numbers[], int array_size)
  2.     {
  3.       q_sort(numbers, 0, array_size - 1);
  4.     }


  5.     void q_sort(int numbers[], int left, int right)
  6.     {
  7.       int pivot, l_hold, r_hold;

  8.       l_hold = left;
  9.       r_hold = right;
  10.       pivot = numbers[left];
  11.       while (left < right)
  12.       {
  13.         while ((numbers[right] >= pivot) && (left < right))
  14.           right--;
  15.         if (left != right)
  16.         {
  17.           numbers[left] = numbers[right];
  18.           left++;
  19.         }
  20.         while ((numbers[left] <= pivot) && (left < right))
  21.           left++;
  22.         if (left != right)
  23.         {
  24.           numbers[right] = numbers[left];
  25.           right--;
  26.         }
  27.       }
  28.       numbers[left] = pivot;
  29.       pivot = left;
  30.       left = l_hold;
  31.       right = r_hold;
  32.       if (left < pivot)
  33.         q_sort(numbers, left, pivot-1);
  34.       if (right > pivot)
  35.         q_sort(numbers, pivot+1, right);
  36.     }
阅读(1020) | 评论(0) | 转发(0) |
0

上一篇:排序-堆排序

下一篇:Apche日志系列

给主人留下些什么吧!~~