请问要怎样才能对一个二维的字符串数组的某一指定的列排序?而且移动时,要整行移动,不能打乱整行顺序。
如:public void sort(String[][] s, int index){} //index指某一指定的列
谁能帮我写一下这方法吗?或者说下其它更好更方便的方法,谢谢了!!~~
如:public void sort(String[][] s, int index){} //index指某一指定的列
谁能帮我写一下这方法吗?或者说下其它更好更方便的方法,谢谢了!!~~
移动时,要整行移动,不能打乱整行顺序数组不同于集合了,移动起来比较麻烦。
下面是一个冒泡排序的解法。 public static void main(String[] args) {
String[][] input = new String[][]{
{"abc", "cde", "aaa"},
{"abc", "123", "aaf"},
{"ab", "444", "abc"},
{"ac", "888", "aaa"}};
sort(input, 2); //第3列作为排序依据,测试
for (String[] row: input){
for (String e: row) System.out.print(e +" ");
System.out.println();
}
} public static void sort(String[][] s, int index){
for (int i = s.length - 1; i > 0; i--) {
for (int j = 0; j < i; j++) {
if (s[j][index].compareTo(s[j + 1][index])>0) {
String[] temp = s[j];
s[j] = s[j+1];
s[j+1] = temp;
}
}
}
}
public static void main(String[] args) {
String[][] str = {{"abc","cde","def"},{"bbc","cdf","dff"},
{"123","123","123"},{"124","321","def"},{"a123","e","sd1f"}};
sort(str,2);
for(int i=0; i<str.length; i++) {
for(int j=0; j<str[i].length; j++) {
System.out.print(str[i][j] + " ");
}
System.out.println();
}
}
public static void sort(String[][] s, int index) {
if(index < 0 || index > s[0].length) {
System.out.println("请输入合适的索引!");
return;
}
String[] temp = new String[s[0].length];
//用冒泡排序来进行排序
for(int i=0; i<s.length; i++) {
for(int j=0; j<s.length - i - 1; j++) {
if(s[j][index].compareTo(s[j+1][index]) > 0) {
temp = s[j];
s[j] = s[j+1];
s[j+1] = temp;
}
}
}
}
}
Arrays.sort(s, new Comparator<String[]>(){
public int compare(String[] arg0, String[] arg1) {
return arg0[index].compareTo(arg1[index]);
}});
}
方法如下:分别用选择和冒泡法实现了。程序有什么不妥指出,请指出来啊,谢谢了!
public class TestSort{
public static void main(String[] args){
int[][] in=new int[][]{
{1,2,3},
{2,3,1},
{3,1,2},
};
print(in);
System.out.println();
selectSort(in,2);
//bubbleSort(in,2);
print(in);
}
private static void selectSort(int[][] in,int n){
int k=0;
int[] temp=null;
for(int i=0;i<in.length;i++){
k=i;
for(int j=k+1;j<in[i].length;j++){
if(in[k][n]>in[j][n]){
k=j;
}
}
if(k!=i){
temp=in[k];
in[k]=in[i];
in[i]=temp;
}
}
}
private static void bubbleSort(int[][] in,int n){
int[] temp=null;
for(int i=in.length-1;i>=0;i--){
for(int j=0;j<i;j++){
if(in[j][n]>in[j+1][n]){
temp=in[i];
in[i]=in[j];
in[j]=temp;
}
}
}
}
private static void print(int[][] in){
for(int i=0;i<in.length;i++){
System.out.print("{");
for(int j=0;j<in[i].length;j++){
System.out.print(in[i][j]);
if(j!=in[i].length-1){
System.out.print(",");
}
}
System.out.println("}");
}
}
}