分享

[Python]python和C语言分别实现快速排序

 思念是一种饼 2011-04-10
代码
from random import Random

def quick_sort(arr):
    
if len(arr) > 1:
        qsort(arr,0,len(arr)
-1)

def qsort(arr,start,end):
    base 
= arr[start]
    pl 
= start + 1
    pr 
= end
    
while True:
        
while arr[pl] > base:
            pl 
+= 1
        
        
while arr[pr] < base:
            pr 
-= 1
        
        
if pl >= pr:
            
break;
        
        arr[pl],arr[pr] 
= arr[pr],arr[pl]
    arr[start] 
= arr[pr]
    arr[pr] 
= base
    
    
if(pr - 1 > start):
        qsort(arr,start,pr 
- 1)
    
if(pl + 1 < end):
        qsort(arr,pr
+1,end)

= Random()
= []
for i in range(20):
    a.append(r.randint(0,
100))

print a
quick_sort(a)
print a

最后结果:

[20, 84, 4, 12, 48, 91, 71, 84, 44, 43, 78, 46, 26, 50, 51, 90, 40, 7, 93, 62]
[93, 91, 90, 84, 84, 78, 71, 62, 51, 50, 48, 46, 44, 43, 40, 26, 20, 12, 7, 4]

C部分:

代码
/*
 * =====================================================================================
 *
 *       Filename:  quickSort.cpp
 *
 *    Description:  quick Sort method
 *
 *        Version:  1.0
 *        Created:  11/25/2010 08:52:33 PM
 *       Revision:  none
 *       Compiler:  gcc
 *
 *         Author:  Archy Yu 
 *        Company:  
 *
 * =====================================================================================
 
*/

#include
<stdio.h>

void swap(int &i,int &j)
{
    
int k = i;
    i 
= j;
    j 
= k;
}

int Partition(int a[3],int left,int right)
{
    
int i = left;
    
int j = right + 1;
    
int tem = a[i];
    
while(true)
    {
        
while(a[++i] < tem);
        
while(a[--j] > tem);

        
if(i >= j)
            
break;

        swap(a[i],a[j]);
    }
    a[left] 
= a[j];
    a[j] 
= tem;
    
return j;
}

void QuickSort(int a[3],int left,int right)
{
    
if(left < right)
    {
        
int part = Partition(a,left,right);
        QuickSort(a,left,part
-1);
        QuickSort(a,part
+1,right);
    }
}

int main()
{
    
int b[3= {9,7,8};
    QuickSort(b,
0,3);
    
for(int i=0;i<=2;i++)
    {
        printf(
"%d ",b[i]);
    }
    
return 0;
}

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多