Wed Dec 19, 2012 7:24 pm
package sort;
public class MergeSort {
public static void main(String a[]) {
int nonSortedArray[] = {532, 4, 2, 18, 354, 25, 17, 51, 3};
// Printing the array
System.out.println(" Before Sorting:");
for (int i = 0; i < nonSortedArray.length; i++) {
System.out.print(nonSortedArray[i] + " , ");
}
System.out.println();
// Merging Sort
for (int i = 1; i < nonSortedArray.length; i *= 2) {
for (int j = 0; j < nonSortedArray.length - i; j += 2 * i) {
int subArrayToBeSortedSize = (2 * i < nonSortedArray.length - j) ? 2 * i : nonSortedArray.length - j;
nonSortedArray = MergeSort(nonSortedArray, j, i, subArrayToBeSortedSize);
}
}
// Output sorted array
System.out.println("After sorting:");
for (int i = 0; i < nonSortedArray.length; i++) {
System.out.print(nonSortedArray[i] + " ");
}
System.out.println();
}
public static int[] MergeSort(int[] myArray, int startIndex, int firstArrayLimit, int secondArrayLimit) {
int i = 0 + startIndex;
int j = firstArrayLimit + startIndex;
int k = 0;
int[] tempArray = new int[secondArrayLimit];
// Compare the two arrays elements
while (i < firstArrayLimit + startIndex && j < secondArrayLimit + startIndex) {
if (myArray[i] < myArray[j]) {
tempArray[k] = myArray[i];
++i;
} else {
tempArray[k] = myArray[j];
++j;
}
++k;
}
// Copy the remaining elements of the 1st array if exists
while (i < firstArrayLimit + startIndex) {
tempArray[k] = myArray[i];
++i;
++k;
}
// Copy the remaining elements of the 2nd array if exists
while (j < secondArrayLimit + startIndex) {
tempArray[k] = myArray[j];
++j;
++k;
}
// Copy the merged part of the array
for (int iIndex = 0; iIndex < secondArrayLimit; ++iIndex) {
myArray[iIndex + startIndex] = tempArray[iIndex];
}
return myArray;
}
}
Codemiles.com is a participant in the Amazon Services LLC Associates Program, an affiliate advertising program designed to provide a means for sites to earn advertising fees by advertising and linking to Amazon.com
Powered by phpBB © phpBB Group.