数组常用排序方法:
import java.util.Arrays;
/*
* Java 自带数组排序Arrays.sort(nums);
* Java自带时钟函数
* startTime = System.currentTimeMillis();//记录毫秒
*/
public class Test
{
public static void main(String[] args)
{
int[] nums = new int[100000];
initArray(nums);//初始化
long startTime = System.currentTimeMillis();//记时间
selectionSort(nums);// 选择排序
long endTime = System.currentTimeMillis();
System.out.println("选择排序时间: " + (endTime - startTime));
initArray(nums);//初始化
startTime = System.currentTimeMillis();
bubbleSort(nums);//冒泡排序
endTime = System.currentTimeMillis();
System.out.println("冒泡排序时间: " + (endTime - startTime) );
//print(nums);
initArray(nums);//初始化
startTime = System.currentTimeMillis();
Arrays.sort(nums);// Arrays.sort()排序
endTime = System.currentTimeMillis();
System.out.println("Arrays.sort() 排序时间 : " + (endTime - startTime) + "\n\n");
//print(nums);
}
private static void initArray(int[] arr)//初始化
{
for (int i = 0; i < arr.length; i++)//初始化
{
arr[i] = ((int)(Math.random()*10000000)) % 10000;
}
}
private static void selectionSort(int[] arr)//选择排序
{
int temp;
int k;
for (int i = 0; i < arr.length; i++)
{
k = i;
for (int j = i+1; j < arr.length; j++)
{
if(arr[j] < arr[k])
k = j;
}
if(i != k)
{
temp = arr[i];
arr[i] = arr[k];
arr[k] = temp;
}
}
}
private static void bubbleSort(int[] arr)//冒泡排序
{
int temp;
for (int i = arr.length - 1; i >= 1; i--)
{
for (int j = 0; j <= i-1; j++)
{
if(arr[i] < arr[j])
{
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
/* for (int i = 0; i < arr.length-1; i ++ )//控制比较轮数
{
for (int j = i + 1; j < arr.length; j++)
{
if(arr[j] < arr[i])
{
tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
}
}
}*/
}
private static void print(int[] arr)
{
for (int i = 0; i < arr.length; i++)
{
System.out.print(arr[i] + " ");
if((i+1) % 10 == 0)
System.out.println();
}
}
}