Java之给出数组求其最大值位置下标
发布网友
发布时间:2022-07-03 04:13
我来回答
共1个回答
热心网友
时间:2023-11-02 09:51
public static void main(String[] ags){
int[] arr = {45, 34, 53, 43};
sortInt(arr);
String[] keys =new String[]{"fin","abc","shidema","shide","bushi"};
sortString(keys);
}
/**
* INT数组排序
* @param arr
*/
private static void sortInt(int... arr){
if(null==arr||arr.length==0){
return;
}
Arrays.sort(arr);
System.out.println("数组排序后:"+Arrays.toString(arr));
System.out.println("数组最大值:"+arr[arr.length-1]);
System.out.println("数组最大值下标:"+(arr.length-1));
}
/**
* 对字符串数组进行排序
* @param keys
* @return
* */
public static void sortString(String... keys){
for (int i = 0; i < keys.length - 1; i++) {
for (int j = 0; j < keys.length - i -1; j++) {
String pre = keys[j];
String next = keys[j + 1];
if(isMoreThan(pre, next)){
String temp = pre;
keys[j] = next;
keys[j+1] = temp;
}
}
}
System.out.print("数组排序后:");
for (String key : keys) {
System.out.print(key+",");
}
System.out.println();
System.out.println("==========================");
System.out.println("数组最大值:"+keys[keys.length-1]);
System.out.println("数组最大值下标:"+(keys.length-1));
}
/**
* 比较两个字符串的大小,按字母的ASCII码比较
* @param pre
* @param next
* @return
* */
private static boolean isMoreThan(String pre, String next){
if(null == pre || null == next || "".equals(pre) || "".equals(next)){
return false;
}
char[] c_pre = pre.toCharArray();
char[] c_next = next.toCharArray();
int minSize = Math.min(c_pre.length, c_next.length);
for (int i = 0; i < minSize; i++) {
if((int)c_pre[i] > (int)c_next[i]){
return true;
}else if((int)c_pre[i] < (int)c_next[i]){
return false;
}
}
if(c_pre.length > c_next.length){
return true;
}
return false;
}