我正在尝试使用预定义的索引数组对ArrayList进行排序。 我当前的示例使用原始ArrayList的副本进行排序,因此不适用于较大对象的ArrayLists
package sortExample;
import java.awt.List;
import java.util.ArrayList;
import java.util.Arrays;
public class sortExample {
public static void main(String[] args) {
String [] str = new String[] {"a","b","c","d"};
ArrayList<String> arr1 = new ArrayList<String>(Arrays.asList(str));
int [] indices = {3,1,2,0};
ArrayList<String> arr2 = new ArrayList(arr1.size());
for (int i = 0; i < arr1.size(); i++) {
arr2.add("0");
}
int arrIndex = 0;
for (int i : indices){
String st = arr1.get(arrIndex);
arr2.set(i, st);
arrIndex++;
}
System.out.println(arr1.toString());
System.out.println(arr2.toString());
}
}
答案 0 :(得分:2)
要重复使用相同的数据,请参阅我的解决方案:
public static void main(String[] args) {
String[] strs = new String[]{"a", "b", "c", "d"};
int[] indices = {3, 1, 2, 0};
String tmp;
for (int i = 0; i < strs.length; i++) {
if (i != indices[i]) {
tmp = strs[i];
strs[i] = strs[indices[i]];
strs[indices[i]] = tmp;
indices[indices[i]] = indices[i];
indices[i] = i;
}
}
for (int i : indices) {
System.out.print(i + " ");
}
System.out.println();
for (String str : strs) {
System.out.print(str + " ");
}
}
输出是:
0 1 2 3
d b c a
答案 1 :(得分:2)
根据周期替换重新排序。请注意,索引将更改为{0,1,2,3}。我还没有安装Java,所以我将工作的C ++代码转换为我认为合适的Java语法。
for (int i = 0; i < arr1.size(); i++) {
if(i != indices[i]) {
String st = arr1.get(i);
int t = indices[i];
int k = i;
int j;
while(i != (j = indices[k])){
arr1.set(k, arr1.get(j));
indices[k] = k;
k = j;
}
arr1.set(k, st);
indices[k] = k;
}
}
对于这个特定情况{3,1,2,0},所有这一切都是交换0和3.旋转索引时发生最长循环,例如{3 0 1 2},在这种情况下st = arr1 [0],arr1 [0] = arr1 [3],arr [3] = arr1 [2],arr1 [2] = arr1 [1],arr1 [1] = st。
答案 2 :(得分:1)
有一个(一点点)更简单的解决方案:
int [] indices = {3,1,2,0};
ArrayList<String> arr2 = new ArrayList<String>();
for (int i = 0; i < arr1.size(); i++) {
arr2.add(arr1.get(indices[i]));
}
答案 3 :(得分:1)
在下面,只需使用&#34; indices&#34;一个新阵列。
public class Sorting {
public static void main(String[] args) {
String [] str = new String[] {"a","b","c","d"};
int [] indices = {3,1,2,0};
String sorted [] = new String [str.length] ;
int i = 0;
for (String string : str) {
sorted[indices[i]] = string;
i++;
}
for (String string : sorted) {
System.out.print(string + " ");
}
}
}
打印:d b c a