9.5 排序: 有一种排序的方法,非常好理解,详见本题的步骤,先找出最大值和最小值,把最小值打印出来后,把它存在另一个数组b当中,再删除此最小值,之后再来一次找出最小值,打印出最小值以后,再把它存在另一个数组b当中,再删除此最小值,这样循环往复,直到做完,你就会发觉,你已经把排了序数放在b数组当中了,而这里的彻底删除最小值的方法就是用比最大值还大一的数来取代最小值。(自己想想为什么?)参考后面的答案你会发觉,按照下面的四步,你已经把一个数组排序了。 i)make a method called getMin to find the minimal value of the array. ii)make a method called getMax to find the maximum value of the array. iii) replace the minimal value with the maximum+1. iiii) sort an array.
public class Test {
static int minPosition=0;//用这个全局变量来记录最小数的位置索引,
public static void main(String[] args) {
int[] a = {6, 12, 7, 23, 4};
int max = getMax(a);
int[] b = new int[a.length];
for (int j = 0; j < a.length; j++) {
int min = getMin(a);
/*把a数组当中最小的值,马克-to-win给替换成max+1,这样就相当于把原来的最小值从这个数组当中彻底清除掉了。整个循环做完,a数组就彻底废了。*/
a[minPosition] = max + 1;
minPosition=0;//把minPosition重置一下, 因为最小的位置已经不是这了。
b[j] = min;//用此方法a数组当中的数就一个一个从小到大捣到b数组当中了
}
for (int j = 0; j < a.length; j++) System.out.println(b[j]);
}
static int getMax(int[] a) {
int max=a[0];
for (int i = 1; i < a.length ; i++) {
if(max<a[i])
{
max=a[i];
}
}
return max;
}
static int getMin(int[] a) {
int min=a[0];
for (int i = 1; i < a.length ; i++) {
if(min>a[i])
{
min=a[i];
minPosition=i;//用这个全局变量来记录最小数的位置索引,
}
}
return min;
}
}
更多请见:https://blog.csdn.net/qq_44639795/article/details/103142934
本文系转载,前往查看
如有侵权,请联系 cloudcommunity@tencent.com 删除。
本文系转载,前往查看
如有侵权,请联系 cloudcommunity@tencent.com 删除。
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有