打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
[Python]python和C语言分别实现快速排序
代码
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;
}
本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
快速排序
C++冒泡排序程序
重温数据结构写的几种常用排序方法,给新手参考 - C/C / 新手乐园
第三十七课 实验八 排序实验
十二之再续:快速排序算法之所有版本的c/c 实现
八种排序算法总结(6)
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服