九月四号《算法笔记》学习
生活随笔
收集整理的這篇文章主要介紹了
九月四号《算法笔记》学习
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
文章目錄
- 1.歸并排序(二路)
- <1>遞歸實現
- <2>非遞歸實現
- 3.快速排序
- 4.隨機數生成
1.歸并排序(二路)
<1>遞歸實現
反復將[left,right]區間分為兩半,對兩個子區間[left,mid],[mid+1,right]分別遞歸進行歸并排序,然后合并為有序序列。
const int maxn=100; //合并兩個子區間 void merge(int A[],int L1,int R1,int L2,int R2){int i=L1,j=L2;int temp[maxn],index=0;while(i<=R1&&j<=R2){if(A[i]<=A[j]){temp[index++]=A[i++]; }else{temp[undex++]=A[j++]; }}//將剩余元素加入序列中while(i<=R1) temp[index++]=A[i++];while(j<=R2) temp[index++]=A[j++];for(i=0;i<index;i++){A[L1+i]=temp[i];} } //將數組當前區間進行歸并排序 void mergeSort(int A[],int left,int right){int mid=(left+right)/2;mergeSort(A,left,mid);mergeSort(A,mid+1,right);merge(A,left,mid,mid+1,right); }<2>非遞歸實現
令排序的區間長度初始step為2,將一組數據劃分n個長度為step的區間,對每個區間進行排序,排序完一次就讓step*2,直到step/2超過n,單側區間大于整個長度結束。
void mergeSort(int A[]){for(int setp=2;step/2<=n;step*=2){for(int i=1;i<=n;i+=step){int mid=i+step/2-1;if(mid+1<=n){//右端點i+step-1算的時候可能會超過nmerge(A,i,mid,mid+1,min(i+step-1.n));}}} }3.快速排序
//對區間劃分 int Partition(int A[],int left,int right){int temp=A[left];while(left<right){while(left<right&&A[right]>temp) right--;A[left]=A[right];while(left<right&&A[left]<=temp) left++;A[right]=A[left];}A[left]=temp;return left; } void quickSort(int A[],int left,int right){if(left<right){int pos=Partition(A,left,right);quickSort(A,left,pos-1);quickSort(A,pos+1,right);} }4.隨機數生成
srand((unsigned)time(NULL));
s=rand();
隨機數生成有范圍大小、
(int)(round(1.0*rand()/RAND_MAX *(b-a)+a)) 隨機生成[a,b];
總結
以上是生活随笔為你收集整理的九月四号《算法笔记》学习的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: error[E0277]: Rust语言
- 下一篇: PROTOTEX: Explaining