shell腳本編程(快速排序)
#!/bin/bash #shell腳本編程之快速排序的實現(以最右邊為元點的思想) a=(8 5 10 3 2 93 4 1 2 3 40 9 61 8 6 29) #a=(0 0 0 0 1 2 3 3 4 4 8 28 30495 921 43716) temp= buff= #交換函數 swap() { buff=${a[$1]} a[$1]=${a[$2]} a[$2]=$buff } fun() { i=$(($1-1)) j=$1 temp=${a[$2]} if test $1 -ge $2 ;then return 2 fi while [ $j -le $2 ];do [ $j -lt $2 ] && while [[ ${a[$j]} -gt $temp ]] ;do j=$(($j+1)) done i=$(($i+1)) swap $i $j j=$(($j+1)) done fun 0 $(($i-1)) fun $(($i+2)) $2 } fun 0 15 for((i=0;i<16;i++)) { echo -n ${a[$i]} " " } echo exit 0
下面是C++快速排序的對照代碼
#include <iostream> using namespace std; void swap(int *a,int *b) { int temp = *a; *a = *b; *b = temp; } void Grial(int a[],int x,int y) { int i=x-1; int j=x; if(x>=y)return; int temp = a[y]; while(j<=y) { while(j<y&&a[j]>a[y]) j++; i++; swap(&a[i],&a[j]); j++; } Grial(a,0,i-1); Grial(a,i+1,y); } int main() { int a[]={4,3,921,30495,28,43716,3,4,0,0,2,0,0,1,8,5}; Grial(a,0,14); for(int i=0;i<15;i++) { cout<<a[i]<<" "; } cout<<endl; }
本文由用戶 xwfw 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!