以下贴出两种实现方式,结果一样,但有些许的差别:
第一种:
1 <script type="text/javascript"> 2 var arr=[6,7,8,3,4,5,9]; 3 function quicksort(left,right){ 4 if(left>right){ 5 return ; 6 } 7 var temp=0; 8 var i=right; 9 var j=left; 10 temp=arr[left]; 11 while(arr[i]>arr[left]){ 12 i--; 13 } 14 while(arr[j]<=arr[left]){ 15 j++; 16 } 17 if(i>j){ 18 temp=arr[i]; 19 arr[i]=arr[j]; 20 arr[j]=temp; 21 quicksort(left,right); 22 } 23 else{ 24 arr[left]=arr[i]; 25 arr[i]=temp; 26 quicksort(left,i-1); 27 quicksort(i+1,right); 28 } 29 } 30 quicksort(0,6); 31 console.log(arr); 32 </script>
第二种:
1 <script type="text/javascript"> 2 var a=[6,7,8,3,4,5,9]; 3 function quicksort(left,right){ 4 var i,j,t,temp; 5 if(left>right){ 6 return; 7 } 8 temp=a[left]; 9 i=left; 10 j=right; 11 while(i!=j){ 12 while(a[j]>=temp&&i<j){ 13 j--; 14 } 15 while(a[i]<=temp&&i<j){ 16 i++; 17 } 18 if(i<j){ 19 t=a[i]; 20 a[i]=a[j]; 21 a[j]=t; 22 } 23 } 24 a[left]=a[i]; 25 a[i]=temp; 26 quicksort(left,i-1); 27 quicksort(i+1,right); 28 return; 29 } 30 quicksort(0,6); 31 console.log(a); 32 </script>
原文地址:https://www.cnblogs.com/mycognos/p/9175906.html
时间: 2024-10-12 12:25:11