Basic Sorting algorithm Java implementation (2)--merge sort

Source: Internet
Author: User

Merge sort: Ascending row

Private <t extends comparable<? Super t>> void Mergesortbyasc (t[] data, int low,int high) {t[] temp;/** if left and right equal, return */if (low = = high) return;/** find length and The middle number */int size = high-low +1;int mid = (low + high)/2;temp = (t[]) (new comparable[size]),/** sorts the data on the left */mergesort (dat A, low, mid);/** sorts the data on the right */mergesort (data, mid + 1, high),/** copy-sorted array */for (int i = 0;i < size; i++) {Temp[i] = data [Low + i];} /** merges two sorted arrays */int left = 0;int Right  = mid-low + 1;for (int i = 0, i < size; i++) {if (right <= high-low) {if (l EFT <= Mid-Low) {if (Temp[left].compareto (Temp[right]) > 0) {data[i + low] = Temp[right + +];} Else{data[i + Low] = Temp[left + +];}} Else{data[i + Low] = Temp[right + +];}} Else{data[i + Low] = Temp[left + +];}}}

Descending rows:

 

Private <t extends comparable<? Super t>> void Mergesortbydesc (t[] data, int low,int high) {t[] temp;/** if left and right equal, return */if (low = = high) return;/** Find length And the middle of that number */int size = high-low +1;int mid = (low + high)/2;temp = (t[]) (new comparable[size]);/** sort the data on the left */mergesortbyd ESC (data, Low, mid),/** sorts the data on the right */mergesortbydesc (data, mid + 1, high),/** copy sorted array */for (int i = 0;i < size; i++) {T Emp[i] = Data[low + i];} /** merges two sorted arrays */int left = 0;int Right  = mid-low + 1;for (int i = 0, i < size; i++) {if (right <= high-low) {if (l EFT <= Mid-Low) {if (Temp[left].compareto (Temp[right]) < 0) {data[i + low] = Temp[right + +];} Else{data[i + Low] = Temp[left + +];}} Else{data[i + Low] = Temp[right + +];}} Else{data[i + Low] = Temp[left + +];}}}

  

Basic Sorting algorithm Java implementation (2)--merge sort

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.