1. 程式人生 > 實用技巧 >以太坊智慧合約課

以太坊智慧合約課

快排(QuickSort)思想:

基於分治法的思想:

1、分解:從數列中取出一個元素作為基準元素,將問題分解為兩個子序列列,左子序列都小於基準元素,右子序列都大於

2、治理:對兩個子序列進行快速排序。

3、合併:將排序後的子序列進行合併,得到原問題的解

 1 #include <iostream>
 2 using namespace std;
 3 int Partition(int r[],int low,int high) {
 4     int i=low,j=high;
 5     int pivot=r[low];
 6     //快速排序思想:
 7      
 8
while(i<j) { 9 while(i<j&&r[j]>pivot) 10 j--; 11 if(i<j) { 12 swap(r[i++],r[j]); 13 } 14 while(i<j&&r[i]<pivot) 15 i++; 16 if(i<j) { 17 swap(r[i],r[j--]); 18 } 19
} 20 return i; 21 } 22 void QuickSort(int A[],int low,int high) { 23 int mid; 24 if(low<high) { 25 mid=Partition(A,low,high); 26 QuickSort(A,low,mid-1); 27 QuickSort(A,mid+1,high); 28 } 29 } 30 int main() { 31 int a[1000]; 32 int N; 33 cout<<"
請輸入要排序的資料個數:"<<endl; 34 cin>>N; 35 cout<<"請輸入資料: "<<endl; 36 for(int i=0; i<N; i++) { 37 cin>>a[i]; 38 } 39 cout<<endl; 40 QuickSort(a,0,N-1); 41 cout<<"排序後的資料: "<<endl; 42 for(int i=0; i<N; i++) 43 cout<<a[i]<<" "; 44 cout<<endl; 45 return 0; 46 }