Java:插入排序和归并排序
程序员文章站
2024-03-17 23:32:34
...
插入排序
import java.util.Scanner;
public class Insertsort {
public static int[] randomarray(int len,int max) {
int[] arr=new int[len];
for(int i=0;i<len;i++)
{
arr[i]=(int)(Math.random()*max);
}
return arr;
}
public static void main(String[] args) {
Scanner scan=new Scanner(System.in);
System.out.printf("请输入随机数组的长度:");
int len=scan.nextInt();
System.out.printf("请输入随机数组的数字最大值:");
int max=scan.nextInt();
int[] arr=randomarray(len,max);
System.out.printf("生成的随机数组为:");
for(int k=0;k<len;k++)
{
System.out.printf("%d ",arr[k]);
if(k==len-1) System.out.println();
}
System.out.printf("排序过程:\n");
for(int i=0;i<len;i++)
{
for(int j=i;j>0;j--)
{
if(arr[j]<arr[j-1])
{
int t;
t=arr[j];
arr[j]=arr[j-1];
arr[j-1]=t;
}
}
for(int k=0;k<len;k++)
{
System.out.printf("%d ",arr[k]);
if(k==len-1) System.out.println();
}
}
scan.close();
}
}
归并排序
import java.util.Scanner;
public class Mergesort {
static int n;
public static int[] randomarray(int len,int max) {
int[] arr=new int[len];
for(int i=0;i<len;i++)
{
arr[i]=(int)(Math.random()*max);
}
return arr;
}
public static void merge(int[] r,int[] r1,int low,int mid,int high) {
int i=low,j=mid+1,k=low;
while((i<=mid)&&(j<=high))
{
if(r[i]<=r[j]) r1[k++]=r[i++];
else r1[k++]=r[j++];
}
while(i<=mid) r1[k++]=r[i++];
while(j<=high) r1[k++]=r[j++];
}
public static void mergepass(int[] r,int[] r1,int len) {
int i=0,j;
while(i+2*len-1<n)
{
merge(r,r1,i,i+len-1,i+2*len-1);
i=i+2*len;
}
if((i+len-1)<n-1) merge(r,r1,i,i+len-1,n-1);
else for(j=i;j<n;j++) r1[j]=r[j];
}
public static void mergesort(int[] r) {
int len=1;
int[] r1=new int[n];
while(len<n)
{
mergepass(r,r1,len);
len=len*2;
mergepass(r1,r,len);
len=len*2;
}
System.out.printf("排序结果:");
for(int k=0;k<n;k++)
{
System.out.printf("%d ",r[k]);
if(k==len-1) System.out.println();
}
}
public static void main(String[] args) {
Scanner scan=new Scanner(System.in);
System.out.printf("请输入随机数组的长度:");
n=scan.nextInt();
System.out.printf("请输入随机数组的数字最大值:");
int max=scan.nextInt();
int[] arr=randomarray(n,max);
System.out.printf("生成的随机数组为:");
for(int k=0;k<n;k++)
{
System.out.printf("%d ",arr[k]);
if(k==n-1) System.out.println();
}
mergesort(arr);
scan.close();
}
}
上一篇: java平台使用脚本语言