題目要求如下:
給定一個數組input[],
如果數組長度n為奇數,則將數組中最大的元素放到output[]數組最中間的位置,
如果數組長度n為偶數,則將數組中最大的元素放到 output[] 數組中間兩個位置偏右的那個位置上,
然后再按從大到小的順序,依次在第一個位置的兩邊,按照一左一右的順序,依次存放剩下的數。
這種處理后結果,如果按照元素的值表示一種分布的圖形的話,那繪制后的圖形應該是正態分布。
關于正態分布:
正態分布(Normal distribution)又名高斯分布(Gaussian distribution),是一個在數學、物理及工程等領域都非常重要的概率分布,在統計學的許多方面有著重大的影響力。若隨機變量X服從一個數學期望為μ、方差為σ^2的高斯分布,記為N(μ,σ^2)。其概率密度函數為正態分布的期望值μ決定了其位置,其標準差σ決定了分布的幅度。因其曲線呈鐘形,因此人們又經常稱之為鐘形曲線。我們通常所說的標準正態分布是μ= 0,σ = 1的正態分布。
這里只是從結果上產生聯系,算法與正態分布無關。
代碼實現如下:
void sort(int input[],int output[], int n) { int m=n; //cout<<m<<endl; int i,j,temp; bool exchange;//交換標志 for(i=0;i<m-1;i++) { //最多做n-1趟排序 exchange=FALSE; //本趟排序開始前,交換標志應為假 for(j=m-2;j>=i;j--) //對當前無序區R[i..n]自下向上掃描 if(input[j+1]<input[j]) {//交換記錄 temp=input[j+1]; //R[0]不是哨兵,僅做暫存單元 input[j+1]=input[j]; input[j]=temp; exchange=TRUE; //發生了交換,故將交換標志置為真 } if(!exchange) //本趟排序未發生交換,提前終止算法 break; //cout<<input[5]<<endl; } for(int wc1=0; wc1<m; wc1++)//只是來顯示排序結果~ { cout<<input[wc1]<<" "; } cout << endl; int q=m-1; if((m%2)==0) { int mid=m/2; for (int tempmid=0; tempmid<=mid; tempmid++)//注意循環語句的執行順序 { output[mid+tempmid]=input[q]; q--; output[mid-tempmid-1]=input[q]; q--; } } if((m%2)!=0)//注意循環語句的執行順序 { int mid=q/2; output[mid]=input[q]; for (int tempmid=1;tempmid<=mid;tempmid++) { q--; output[mid-tempmid]=input[q]; q--; output[mid+tempmid]=input[q]; } } for(int wc=0; wc<m; wc++) { cout<<output[wc]<<" "; } cout << endl; }
int main() { int input[] = {3, 6, 1, 9, 7, 8, 2}; int wc=0; int nCount = sizeof(input)/sizeof(int); for(wc=0; wc<nCount; wc++)// { cout<<input[wc] << " "; //cout<<"/n"<<endl; } cout << endl; int output[]= {3, 6, 1, 9, 7, 8, 2}; sort(input,output, nCount); return 0; }
測試結果:
當int input[] = {3, 6, 1, 9,7, 8, 2, 10};,結果如下:
3 6 1 9 7 8 2 10
1 2 3 6 7 8 9 10
1 3 7 9 10 8 6 2
當int input[] = {3, 6, 1, 9,7, 8, 2, 10};,結果如下:
3 6 1 9 7 8 2
1 2 3 6 7 8 9
2 6 8 9 7 3
新聞熱點
疑難解答