public class MergeSort
{
static void MergeSort(double a[], int N)
{
double [] temp = new double[N];
int len = 32, i, j, k;
//分段进行直插排序,生成初始为len长的归并段
for (k = 1; k < N; k += len)
{
for (i = k; i < k + len - 1 && i < N; i++) //为了避免i<N这个判断,可以对原序列剩余小于len的序列另写一个直插
{
double temp1 = a[i];
for (j = i; j >= k && temp1 < a[j - 1]; j--) {
a[j] = a[j - 1];
}
a[j] = temp1;
}
}
while (len < N) //固定执行偶数次MergePass,最后的结果在原来的数组里
{
MergePass(a, temp, len, N);
len *= 2;
MergePass(temp, a, len, N);
len *= 2;
}
}
static void Merge(double S[], double D[], int l, int m, int n)
{
//S[]源表,D[]归并后的表,l源表第一个段的起始序号,m源表第二个段的起始序号,n源表的长度
int i = l, j = m, k = l;//i第一段的指针,j第二段的指针,k目的表指针
for (; i < m && j < n; k++)
if ( S[i] > S[j]) { D[k] = S[j]; j++; } else { D[k] = S[i]; i++; }
if (i < m)
for (; i < m; i++, k++) D[k] = S[i];
else
for (; j < n; j++, k++) D[k] = S[j];
}
static void MergePass(double S[], double D[], int len, int N)
{
int i = 0;
for (; i+2*len < N; i += 2*len) Merge(S, D, i, i+len, i+2*len);
if (i+len < N) Merge(S, D, i, i+len, N);//剩余多于一个len,再做一次归并
else for (; i < N; i++) D[i] = S[i];//少于等于一个len,直接复制
}
public static void main(String[] args)
{
double a[] = new double[]{1,4,2,3,5,9,5,4,2,4,5,6,4,3,3,5,7,8,9,4,3,23,2,1,10};
MergeSort(a,25);
for(int i = 0;i <a.length; i++)
{
System.out.print(" "+ a[i]);
}
}
}
{
static void MergeSort(double a[], int N)
{
double [] temp = new double[N];
int len = 32, i, j, k;
//分段进行直插排序,生成初始为len长的归并段
for (k = 1; k < N; k += len)
{
for (i = k; i < k + len - 1 && i < N; i++) //为了避免i<N这个判断,可以对原序列剩余小于len的序列另写一个直插
{
double temp1 = a[i];
for (j = i; j >= k && temp1 < a[j - 1]; j--) {
a[j] = a[j - 1];
}
a[j] = temp1;
}
}
while (len < N) //固定执行偶数次MergePass,最后的结果在原来的数组里
{
MergePass(a, temp, len, N);
len *= 2;
MergePass(temp, a, len, N);
len *= 2;
}
}
static void Merge(double S[], double D[], int l, int m, int n)
{
//S[]源表,D[]归并后的表,l源表第一个段的起始序号,m源表第二个段的起始序号,n源表的长度
int i = l, j = m, k = l;//i第一段的指针,j第二段的指针,k目的表指针
for (; i < m && j < n; k++)
if ( S[i] > S[j]) { D[k] = S[j]; j++; } else { D[k] = S[i]; i++; }
if (i < m)
for (; i < m; i++, k++) D[k] = S[i];
else
for (; j < n; j++, k++) D[k] = S[j];
}
static void MergePass(double S[], double D[], int len, int N)
{
int i = 0;
for (; i+2*len < N; i += 2*len) Merge(S, D, i, i+len, i+2*len);
if (i+len < N) Merge(S, D, i, i+len, N);//剩余多于一个len,再做一次归并
else for (; i < N; i++) D[i] = S[i];//少于等于一个len,直接复制
}
public static void main(String[] args)
{
double a[] = new double[]{1,4,2,3,5,9,5,4,2,4,5,6,4,3,3,5,7,8,9,4,3,23,2,1,10};
MergeSort(a,25);
for(int i = 0;i <a.length; i++)
{
System.out.print(" "+ a[i]);
}
}
}