Java

Moderators: zibadian
Number of threads: 7832
Number of posts: 18231

This Forum Only
Post New Thread
Single Post View       Linear View       Threaded View      f

Report
Merge sort.. help me plz Posted by doubleuk on 17 May 2011 at 5:11 AM
I have to change this 2-way partitioning merge sort to the 4-way partitioning merge sort.. how can I change??

public class Merge {

public static void sort(int[] a) {
if (a.length >= 2) {
int halfLength = a.length / 2;
int[] firstHalf = new int[halfLength];
int[] lastHalf = new int[a.length - halfLength];

divide(a, firstHalf, lastHalf);
sort(firstHalf);
sort(lastHalf);
merge(a, firstHalf, lastHalf);
}
}

private static void divide(int[] a, int[] firstHalf, int[] lastHalf) {
for (int i = 0; i < firstHalf.length; i++)
firstHalf[i] = a[i];
for (int i = 0; i < lastHalf.length; i++)
lastHalf[i] = a[firstHalf.length + i];
}

private static void merge(int[] a, int[] firstHalf, int[] lastHalf) {
int firstHalfIndex = 0, lastHalfIndex = 0, aIndex = 0;
while ((firstHalfIndex < firstHalf.length)
&& (lastHalfIndex < lastHalf.length)) {
if (firstHalf[firstHalfIndex] < lastHalf[lastHalfIndex]) {
a[aIndex] = firstHalf[firstHalfIndex];

firstHalfIndex++;
} else {
a[aIndex] = lastHalf[lastHalfIndex];

lastHalfIndex++;
}
aIndex++;
}
while (firstHalfIndex < firstHalf.length) {
a[aIndex] = firstHalf[firstHalfIndex];
aIndex++;
firstHalfIndex++;
}
while (lastHalfIndex < lastHalf.length) {
a[aIndex] = lastHalf[lastHalfIndex];
aIndex++;
lastHalfIndex++;
}
}
public static void main(String[] args){
int[] arr = { 3,9,2,1,10,11,6,4,15 };

Merge.sort(arr);

for (int i = 0; i < arr.length; i++) {
System.out.println(arr[i] + " ");
}

}
}



 

Recent Jobs

Official Programmer's Heaven Blogs
Web Hosting | Browser and Social Games | Gadgets

Popular resources on Programmersheaven.com
Assembly | Basic | C | C# | C++ | Delphi | Flash | Java | JavaScript | Pascal | Perl | PHP | Python | Ruby | Visual Basic
© Copyright 2011 Programmersheaven.com - All rights reserved.
Reproduction in whole or in part, in any form or medium without express written permission is prohibited.
Violators of this policy may be subject to legal action. Please read our Terms Of Use and Privacy Statement for more information.
Operated by CommunityHeaven, a BootstrapLabs company.