归并排序

    xiaoxiao2022-07-02  115

    #include <iostream> using namespace std; void merge(int *a,int s,int e,int *b) { int left_len=(e-s+1)/2+1; int left_index=s; int right_index=s+left_len; int result_index=s; while(left_index<s+left_len && right_index<=e) { if(a[left_index]<=a[right_index]) b[result_index++]=a[left_index++]; else b[result_index++]=a[right_index++]; } while(left_index<s+left_len) b[result_index++]=a[left_index++]; while(right_index<=e) b[result_index++]=a[right_index++]; } void sort(int *a,int s,int e,int *b) { if(e-s == 1) { if(a[s]>a[e]) { int t=a[s]; a[s]=a[e]; a[e]=t; } return;//必须放在if条件外 } else if(e-s == 0) return; else { sort(a,s,(e-s+1)/2+s,b); sort(a,(e-s+1)/2+s+1,e,b); merge(a,s,e,b); for(int i=s; i<=e; i++) a[i]=b[i]; } } int main() { int data[] = {9,6,7,22,20,33,16,20}; const int length = 8; int re[length]; sort(data, 0, length-1, re); for(int i=0; i<length; i++) //排序后的数组 cout<<data[i]<<" "; cout<<endl; }
    最新回复(0)