我正在尝试使用两个线程进行Array sort / merg。但不知何故它不起作用(仍然没有排序数组)可能是由于对线程或其他东西的一些误解。很高兴得到你的帮助。 ps:我必须使用两个线程,因为它是分配所必需的。
原始代码
public void sort(int[] data, int lo, int hi)
{
if (lo < hi) {
// divide into two halves
int mid = (lo + hi) / 2;
// sort the two half recursively
sort(data, lo, mid);
sort(data, mid+1, hi);
//Combine the two halves
merge(data, lo, hi, mid);
}
}
private static void merge(int[] data, int lo, int hi, int m)
{
.....
这就是我的工作
public class Sort
{
public void sort(int[] data, int lo, int hi)
{
if (lo < hi) {
int mid = (lo + hi) / 2;
Thread t1=new Thread(new Runnable() {
public void run() {
sort(data, lo, mid);
}
});
Thread t2=new Thread(new Runnable(){
public void run() {
sort(data, mid+1, hi);
}
});
t1.start();
t2.start();
try {
t1.join();
t2.join();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// Combining two halves
merge(data, lo, hi, mid);
}
}
private static void merge(int[] data, int lo, int hi, int m)
{
int[] temp = new int[hi - lo + 1];
int i = lo;
int j = m+1;
int k = 0;
while(k < temp.length) {
if (i <= m) {
if (j <= hi) {
if (data[i] < data[j])
temp[k++] = data[i++];
else
temp[k++] = data[j++];
} else
temp[k++] = data[i++];
} else
temp[k++] = data[j++];
}
for (k = lo; k<=hi; k++)
data[k] = temp[k - lo];
}