Java implementation of MergeSort

Source: Internet
Author: User

This is my first time to write a blog, I also hope that through the process of blogging, and everyone (perhaps know, perhaps do not know, never mind) to share my experience and feelings.

This is the Java implementation of MergeSort. Just started to get some idea of sort.

So refer to some of the online experience and share, write their own writing. and integrate it down.


Package sorting;

public class Mymergesort {

Private int[] array;

Private int[] Tempmergarr;

private int length;


public static void Main (String a[]) {

Int[] Inputarr = {45,230,11,89,77,98,4,28,65,43};

Mymergesort MMS = new Mymergesort ();

Mms.sort (Inputarr);

for (int i:inputarr) {

System.out.print (i);

System.out.print ("");

}

}

public void sort (int inputarr[]) {

This.array = Inputarr;

This.length = Inputarr.length;

This.tempmergarr = new Int[length];

System.out.println (Tempmergarr);

Domergesort (0, length-1);

}


private void Domergesort (int lowerindex, int higherindex) {

if (Lowerindex < Higherindex) {

int middle = Lowerindex + (higherindex-lowerindex)/2;

Below Step sorts the left side of the array

Domergesort (Lowerindex, middle);

Below Step sorts the right side of the array

Domergesort (middle + 1, higherindex);

Now merge both sides

Mergeparts (Lowerindex, Middle, higherindex);

}

}


private void Mergeparts (int lowerindex, int middle, int higherindex) {


for (int i = lowerindex; I <= higherindex; i++) {

Tempmergarr[i] = Array[i];

}

int i = Lowerindex;

Int J = middle + 1;

int k = Lowerindex;

while (I <= Middle && J <= Higherindex) {

if (Tempmergarr[i] <= tempmergarr[j]) {

ARRAY[K] = Tempmergarr[i];

i++;

} else {

ARRAY[K] = Tempmergarr[j];

j + +;

}

k++;

}

while (I <= middle) {

ARRAY[K] = Tempmergarr[i];

k++;

i++;

}


}

}


Java implementation of MergeSort

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.