package select;
/**
* 需求:直接选择排序
* 方法:将数据分为有序区和无序区,然后从无序区选一个最小元素,放在有序区的最后
* 步骤:设数组为a[0...n-1]
* 1、初始时,数组全为无序区a[0...n-1],令i=0;
* 2、在无序区a[i...n-1]中选择一个最小元素,并将其与a[i],交换之后a[0...i]就形成了一个有序区
* 3、i++重复2的步骤
* @author AbuGe
*
*/
public class SelectSort
{
//升序,每次循环都将无序区的最小元素放在有序区
public static void selectSrot(int[] a)
{
int minElementIndex = 0;
int len = a.length;
for(int i = 0; i < len; i++)
{
minElementIndex = i;
for(int j = i + 1; j < len; j++)
{
if(a[j] < a[minElementIndex])
{
minElementIndex = j;
}
}
swap(a, i, minElementIndex);
}
}
public static void swap(int[] a , int x, int y)
{
int tmp = a[x];
a[x] = a[y];
a[y] = tmp;
}
public static void main(String[] args)
{
int[] a = {3, 88, 96, 84, 12, 47, 92, 16};
System.out.println("排序前:");
for(int x : a)
{
System.out.print(x + " ");
}
System.out.println();
selectSrot(a);
System.out.println("排序后:");
for(int x : a)
{
System.out.print(x + " ");
}
}
}
阿布学排序之直接选择排序
最新推荐文章于 2024-08-21 07:00:00 发布