Java:一維數組排序

package mypackage;

public class Hello {
	public static int[] random(int n,int range){  				//聲明n爲常量,方法體中不能賦值
		int[] x=new int[n];   							//聲明一個一維數組,並且爲它申請空間
		while(n>0)
			x[--n]=(int)(Math.random()*range);
		
		return x;
	}
	public static int[] random(){						//方法重載
		return random(10,100);
	}
	//輸出一維數組
	public static void print(final int[] x){		//聲明value數組爲常量,方法體中不能更改引用	
		System.out.print("{");
		if(x.length>0)
			System.out.print(x[0]);
		
		for(int i=0;i<x.length;i++)
			System.out.print(","+x[i]);
		
		System.out.print("}");
	}
	
	public static void selectSort(int[] x){				//選擇排序
		for(int i=0;i<x.length-1;i++){
			int min=i;
			for(int j=i;j<x.length;j++){
				if(x[j]<x[min]){
					min=j;
				}
			}
			if(i!=min){
				int temp=x[i];
				x[i]=x[min];
				x[min]=temp;
			}
		}
	}
	public static int[] merge(int[] x,int[] y){			//將兩個數組合併爲一個數組
		int z[]=new int[x.length+y.length],i=0,j=0,k=0;
		while(i<x.length&&j<y.length)
			if(x[i]<y[i])
				z[k++]=x[i++];
			else
				z[k++]=y[j++];
		while(i<x.length)
			z[k++]=x[i++];
		while(j<y.length)
			z[k++]=y[j++];
		return z;
	}
	public static void main(String[] args) {
		int n1=7,range1=100;
		int[] value1=random(n1,range1),value2=random(6,100);  //產生隨機數
		System.out.print("value1:");  print(value1);
		System.out.print("value2:");  print(value2);
		selectSort(value1); selectSort(value2);
		System.out.print("sorted value1:");  print(value1);
		System.out.print("sorted value2:");  print(value2);
		System.out.print("merge:");  print(merge(value1,value2));
	}

}

【運行結果】
在這裏插入圖片描述

發佈了31 篇原創文章 · 獲贊 2 · 訪問量 5162
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章