归并排序,根据值对数组索引进行排序。
index[]记录数组的索引,aux[]是辅助数组,用于对索引进行归并
import java.util.Arrays;
/**
* @Auther: dzy
* @Date: 2022/2/27 10:04
* @Description: 归并排序,根据数值来给索引排序,主要用于成绩排学号
*/
public class MergeShowIndex {
private MergeShowIndex(){}
public static int[] indexSort(Comparable[] a){
int[] index = new int[a.length];
//辅助数组,类型与进行归并的数据的类型有关
int[] aux = new int[a.length];
for (int i = 0; i < a.length; i++){
index[i] = i;
}
indexSort(a, index, aux, 0, a.length-1);
return index;
}
private static void indexSort(Comparable[] a, int[] index, int[] aux, int low, int hi){
if (low >= hi) return ;
int mid = low + (hi - low) / 2;
indexSort(a, index, aux, low, mid);
indexSort(a, index, aux, mid + 1, hi);
merge(a, index, aux, low, mid, hi);
}
private static boolean less(Comparable a, Comparable b) {return a.compareTo(b) < 0;}
private static void merge(Comparable[] a, int[] index, int[] aux, int low, int mid, int hi) {
for (int i = low; i <= hi; i++){
aux[i] = index[i];
}
int i = low;
int j = mid + 1;
for (int k = low; k <= hi; k++){
if (i > mid) index[k] = aux[j++];
else if (j > hi) index[k] = aux[i++];
else if (less(a[aux[i]],a[aux[j]])) index[k] = aux[i++]; //通过索引找到数组值并比较
else index[k] = aux[j++];
}
}
public static void main(String[] args) {
Comparable[] a = new Comparable[]{2,4,6,3,5,2,1};
int[] index = indexSort(a);
System.out.println("索引序列"+Arrays.toString(index));
StringBuilder s = new StringBuilder();
for (int i = 0;i < index.length; i++){
s.append(a[index[i]]);
}
System.out.println("将值排序后应得的序列: "+s.toString());
}
}