描述:
输入整型数组和排序标识,对其元素按照升序或降序进行排序。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