码迷,mamicode.com
首页 > 编程语言 > 详细

入门之快速排序

时间:2017-07-23 11:26:53      阅读:211      评论:0      收藏:0      [点我收藏+]

标签:namespace   quick   str   names   include   log   问题   []   swa   

 1 /*
 2 入门之快速排序
 3 时间复杂度:O(nlogn)
 4 最坏情况时时间复杂度能达到O(n^2)
 5 借鉴自算法导论
 6 */
 7 #include<iostream>
 8 using namespace std;
 9 int a[] = {3,7,8,5,4,6,2,1,3};
10 void quick_sort(int*,int,int);
11 void swap(int,int);
12 void print();
13 int main()
14 {
15     print();//排序前
16     quick_sort(a,0,8);
17     print();//排序后
18 }
19 void print()
20 {
21     for(int i=0; a[i]!=0; ++i)
22         cout << a[i] << " ";
23     cout << endl;
24 }
25 void swap(int x,int y)
26 {
27     int t = a[x];
28     a[x] = a[y];
29     a[y] = t;
30 }
31 void quick_sort(int a[],int l,int r)//将 <t 和 >=t 的分开
32 {
33     if(l >= r)
34         return ;
35     int t = a[r],j = l-1;//边界问题
36     for(int i=l; i<r; ++i)
37         if(a[i] < t)
38         {
39             ++j;
40             if(i != j)
41                 swap(i,j);
42         }
43     swap(j+1,r);
44     quick_sort(a,l,j);
45     quick_sort(a,j+2,r);
46 }

 

入门之快速排序

标签:namespace   quick   str   names   include   log   问题   []   swa   

原文地址:http://www.cnblogs.com/qq188380780/p/7223759.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!