快速排序算法实现

    技术2022-05-13  3

    $data = array(39,42,20,38,50,35,69,78,164,85,79); function pt($low,$high) { global $data; $tmp = $data[$high]; if($high<=$low) return; while($low<$high) { while($low<$high && $tmp>=$data[$low]){ $low++; } $data[$high] = $data[$low]; while($low<$high && $tmp<=$data[$high]) { $high--; } $data[$low] = $data[$high]; } $data[$low] = $tmp; return $low; } function q($low,$high) { if($low < $high) { $k = pt($low,$high); q($low,$k-1); q($k+1,$high); } } q(0,count($data)-1); print_r($data);

     

    //用c实现的qsort #include <stdio.h> static int data[]={24,95,80,20,30,60,40,34,150}; void qsort(int low,int high) { if(low>high) return; int prive = data[low]; int i = low; int j=high; while(i<j){ while(i<j && data[j]>prive){ j--; } data[i]=data[j]; while(i<j && data[i]<prive){ i++; } data[j]=data[i]; } data[i] = prive; if(i-1>low){ qsort(low,i-1); } if(i+1<high){ qsort(i+1,high); } } int main() { int len = sizeof(data)/4; qsort(0,len-1); int i; for(i=0;i<len;i++){ printf("%d/n",data[i]); } return 0; }


    最新回复(0)