An Implementation of Merge Sort in C

來源:互聯網
上載者:User

Following C code is the implementation of merge sort, with the time complexity of O(nlogn). It was used in my current project to sort 148 million integers. At first I used bubbled sort, which took me hours to have the 148M integers sorted, because the time complexity of bubble sort is O(n^2). After replacing the sorting algorithm with merge sort, the time of sorting reduced to less than 10 mins. Amazing improvement! Although I have heard of the importance of sorting/searching algorithm for years, it was the first time I realize the magic of algorithms. 

The merge sort below was found in Internet. Sorry that I forgot to record the hyperlink of the webpage. Only a few changes were made by me. 

void Merge(int* input, long p, long r){long mid = floor((p + r) / 2);long i1 = 0;long i2 = p;long i3 = mid + 1;// Temp arrayint* temp=new int[r-p+1];// Merge in sorted form the 2 arrayswhile ( i2 <= mid && i3 <= r )if ( input[i2] < input[i3] )temp[i1++] = input[i2++];elsetemp[i1++] = input[i3++];// Merge the remaining elements in left arraywhile ( i2 <= mid )temp[i1++] = input[i2++];// Merge the remaining elements in right arraywhile ( i3 <= r )temp[i1++] = input[i3++];// Move from temp array to master arrayfor ( int i = p; i <= r; i++ )input[i] = temp[i-p];delete [] temp;}// inputs://p - the start index of array input//r - the end index of array inputvoid Merge_sort(int* input, long p, long r){if ( p < r ){long mid = floor((p + r) / 2);Merge_sort(input, p, mid);Merge_sort(input, mid + 1, r);Merge(input, p, r);}}



聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.