sort
package Sort;import java.util.Random;
public class SelectionSort {
/**
*
*选择排序法、
*
**/
//形参:数组名
public void SelectionSort(int[] a){
int temp;
for(int i = 0;i<a.length-1;i++)
{
int index = getMinIndex(a,i);
if(index != i){//如果得到的不是第一个元素的下标则交换(可以提高效率)
temp = a[i];
a[i]=a[index];
a[index]=temp;
}
}
for(int i = 0;i<a.length;i++){
System.out.println(a[i] + " ");
}
}
/** *
* 输入参数:数组名、开始序号,返回最小元素的下标、
* **/
private int getMinIndex(int[] a, int j) {
int min = a[j];
int index = j;
for(int i = j;i<a.length;i++){
if(a[i]<min){
min = a[i];
index = i;
}
}
return index;
}
public static void main(String[] args) {
int a[] = new int[10000];
Random ran = new Random();
for(int i=0;i<9999;i++){
a[i] = ran.nextInt(10000);
if(i % 100==0)
System.out.println("");
System.out.print(a[i] + " ");
}
long starttime = System.currentTimeMillis();
SelectionSort ss = new SelectionSort();
ss.SelectionSort(a);
long endtime = System.currentTimeMillis();
System.out.println("排序共花费"+(endtime-starttime)+"毫秒");
}
}
sort
package Sort;import java.util.Random;
public class SelectionSort {
/**
*
*选择排序法、
*
**/
//形参:数组名
public void SelectionSort(int[] a){
int temp;
for(int i = 0;i<a.length-1;i++)
{
int index = getMinIndex(a,i);
if(index != i){//如果得到的不是第一个元素的下标则交换(可以提高效率)
temp = a[i];
a[i]=a[index];
a[index]=temp;
}
}
for(int i = 0;i<a.length;i++){
System.out.println(a[i] + " ");
}
}
/** *
* 输入参数:数组名、开始序号,返回最小元素的下标、
* **/
private int getMinIndex(int[] a, int j) {
int min = a[j];
int index = j;
for(int i = j;i<a.length;i++){
if(a[i]<min){
min = a[i];
index = i;
}
}
return index;
}
public static void main(String[] args) {
int a[] = new int[10000];
Random ran = new Random();
for(int i=0;i<9999;i++){
a[i] = ran.nextInt(10000);
if(i % 100==0)
System.out.println("");
System.out.print(a[i] + " ");
}
long starttime = System.currentTimeMillis();
SelectionSort ss = new SelectionSort();
ss.SelectionSort(a);
long endtime = System.currentTimeMillis();
System.out.println("排序共花费"+(endtime-starttime)+"毫秒");
}
}