数组排序后 原数组元素的排名
/**
*@Title : SortEnum.java
*@Description : TODO
*@date : 2019年9月24日上午10:23:14
*@version : 1.0
*/
public class SortEnum {
private int origInd;
private int newInd;
private Integer value;
/**
* 给数组中的每个元素添加原位置、新位置信息
* @param arr
* @return
* @Date 2019年9月24日 上午10:58:11
*/
public static SortEnum[] getArray(Integer[] arr){
SortEnum[] ret = new SortEnum[arr.length];
SortEnum row = null;
for (int i = 0; i < arr.length; i++) {
row = new SortEnum(i,i,arr[i]);
ret[i] = row;
}
return ret;
}
/**
*
* @param arr
* @param equalRank 是否需要等值排名
* @Date 2019年11月4日 下午7:49:15
*/
public static void bubbleSort(SortEnum[] arr,boolean equalRank) {
SortEnum temp;//定义一个临时变量
for(int i=0;i<arr.length-1;i++){//冒泡趟数
for(int j=0;j<arr.length-i-1;j++){
//如果顺序不对,则交换两个元素
if(arr[j+1].getValue()>arr[j].getValue()){
temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
}
int pos = 0;
for (int i = 0; i < arr.length; i++) {
if(equalRank) {//等值并列排名
if(i>0 && arr[i].getValue()<arr[i-1].getValue()) {
pos++;
}
arr[i].setNewInd(pos);
}else {
arr[i].setNewInd(i);
}
}
}
/**
* @return the origInd
*/
public int getOrigInd() {
return origInd;
}
/**
* @param origInd the origInd to set
*/
public void setOrigInd(int origInd) {
this.origInd = origInd;
}
/**
* @return the newInd
*/
public int getNewInd() {
return newInd;
}
/**
* @param newInd the newInd to set
*/
public void setNewInd(int newInd) {
this.newInd = newInd;
}
/**
* @return the value
*/
public Integer getValue() {
return value;
}
/**
* @param value the value to set
*/
public void setValue(Integer value) {
this.value = value;
}
/**
* @param origInd
* @param newInd
* @param value
*/
public SortEnum(int origInd, int newInd, Integer value) {
super();
this.origInd = origInd;
this.newInd = newInd;
this.value = value;
}
@Override
public String toString() {
return this.value+"("+this.origInd+","+this.newInd+")";
}
}
调用:
Integer[] arr = {10,21,11,56,41,25,13,24,21};
SortEnum[] arr1 = SortEnum.getArray(arr);
SortEnum.bubbleSort(arr1,true);
System.out.println(Arrays.deepToString(arr1));
//输出
[56(3,0), 41(4,1), 25(5,2), 24(7,3), 21(1,4), 21(8,4), 13(6,5), 11(2,6), 10(0,7)]

浙公网安备 33010602011771号