首页 > 其他 > 详细

利用Arrays.sort(Array,Comparator)对数组进行排序

时间:2014-03-04 07:08:05      阅读:543      评论:0      收藏:0      [点我收藏+]
描述:
输入整型数组和排序标识,对其元素按照升序或降序进行排序。0为升序,1为降序。

分析:
对数组的排序,按照前面某篇文章里讲过的两种方法足以,但可以利用Arrays.sort(Array,Comparator)进行排序。
大大简化了代码。

代码如下:
普通排序方法:
public static void sortArray(Integer[] pIntegerArray, int sortFlg)
    {
    if (pIntegerArray == null)
    {
    return;
    }
    int temp = 0;
    if (sortFlg == 0)
    {
    boolean flag = true;
    while (flag)
    {
    flag = false;
    for (int j=0;j+1<pIntegerArray.length;j++)
    {
    if (pIntegerArray[j] > pIntegerArray[j+1])
    {
    flag = true;
    temp = pIntegerArray[j+1];
    pIntegerArray[j+1] = pIntegerArray[j];
    pIntegerArray[j] = temp;
    }
    }
    }
    return;
    }
    else
    {
    boolean flag = true;
    while (flag)
    {
    flag = false;
    for (int j=0;j+1<pIntegerArray.length;j++)
    {
    if (pIntegerArray[j] < pIntegerArray[j+1])
    {
    flag = true;
    temp = pIntegerArray[j+1];
    pIntegerArray[j+1] = pIntegerArray[j];
    pIntegerArray[j] = temp;
    }
    }
    }
    return;
    }
    }

利用Arrays.sort(Array,Comparator)进行排序:
public static void sortArray(Integer[] pIntegerArray, int sortFlg)
{
if (sortFlg == 0)
{
Arrays.sort(pIntegerArray);//默认为升序
/*
即等价于:
Arrays.sort(pIntegerArray, new Comparator<Integer>
{
public int compare(Integer a, Integer b)
{
return a.compareTo(b);//升序
}
});
*/
}
else
{
Arrays.sort(pIntegerArray, new Comparator<Integer>
{
public int compare(Integer a, Integer b)
{
return b.compareTo(a);
}
});
}
}

利用Arrays.sort(Array,Comparator)对数组进行排序,布布扣,bubuko.com

利用Arrays.sort(Array,Comparator)对数组进行排序

原文:http://blog.csdn.net/lanximu/article/details/20377085

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!