用选择的方式对数组进行排序,并写出对应的优化后的代码实现。(重点写思路、原理)

来源:互联网 发布:ubuntu安装tar.gz软件 编辑:程序博客网 时间:2024/06/10 05:46
class s1
{
/*
选择排序的比较方式:首先选择一个位置,让该位置上的数与下一个位置上的数进行比较,两者比较后取最值占取该位置,
并用该位置上的值继续去和下一个位置上的值继续比较。
原理:如果第一次选择了0角标上的值,那么第一次循环比较后,最值会出现在0角标的位置上。
*/
    public static void selectSort(int arr[])
{
for (int x=0;x<arr.length-1;x++)
{
for (int y=x+1;y<arr.length;y++)
{
if (arr[x]>arr[y])
{
swap(arr,x,y);
}
}
}
}
public static void swap(int arr[],int a,int b)
{
int temp = arr[a];
arr[a] = arr[b];
arr[b] = temp;
}
public static String arrayToString(int arr[])
{
     String str="{";
 for (int x=0;x<arr.length;x++)
 {
if (x!=arr.length-1)
{
               str=str+arr[x]+",";
}
else
str=str+arr[x]+"}";
 }
 return str;
}
public static void main(String[] args)
{
int arr[]={9,2,4,8,5,6,7,3,1};
selectSort(arr);
System.out.print(arrayToString(arr));
}


}
原创粉丝点击