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

qsort,mergesort,插入排序

时间:2015-02-12 22:39:01      阅读:233      评论:0      收藏:0      [点我收藏+]

标签:

 1     //插入排序 
 2     int a[n];
 3     for(int i=2;i<=n;i++)
 4     {
 5         int s=a[i];
 6         int j=i-1;
 7         while(j&&a[j]>a[i])
 8         {
 9             a[j+1]=a[j];
10             j--;
11         }
12         a[j+1]=s;
13     } 
14     
15     
16 int part(int a[],int low,int high)
17 {
18     int tmp=a[low];
19     while(low<high)
20     {
21         while(low<high&&a[high]>=tmp)
22             high--;
23         if(low<high)
24         {
25             a[low]=a[high];
26             low++;
27         }
28         while(low<high&&a[low]<=tmp)
29             low++;
30         if(low<high)
31         {
32             a[high]=a[low];
33             high--;
34         }
35     }
36     a[low]=tmp;
37     return low;
38 }
39 
40 void quick_sort(int a[],int low,int high)
41 {
42     int mid;
43     if(low<high)
44     {
45         mid=(low+high)/2;
46         mid=part(a,low,high);
47         quick_sort(a,low,mid-1);
48         quick_sort(a,mid+1,high);
49     }
50     return ;
51 }
52 
53 /************归并************/
54 void merge(int a[],int low,int high)
55 {
56     int b1=low;
57     int mid=(low+high)/2;
58     int b2=mid+1;
59     int len=high-low+1;
60     int *b,k=0;
61     b=(int *)malloc(len*sizeof(int));
62     while(b1<=mid&&b2<=high)
63     {
64         if(a[b1]<=a[b2])
65             b[k++]=a[b1++];
66         else
67             b[k++]=a[b2++];
68     }
69     while(b1<=mid)
70         b[k++]=a[b1++];
71     while(b2<=high)
72         b[k++]=a[b2++];
73     for(int i=0;i<len;i++)
74         a[low++]=b[i];
75     free(b);
76 }
77 
78 void merge_sort(int a[],int low,int high)
79 {
80     int mid=(low+high)/2;
81     if(low<high)
82     {
83         merge_sort(a,low,mid);
84         merge_sort(a,mid+1,high);
85         merge(a,low,high);
86     }
87     return ;
88 }

 

qsort,mergesort,插入排序

标签:

原文地址:http://www.cnblogs.com/767355675hutaishi/p/4288919.html

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