62,621
社区成员
发帖
与我相关
我的任务
分享
public class Test {
public static void main(String[] args) {
String[] s ={"张三","李四","王五"};
int[] c ={20,18,19};
selectSort(c,s);
for(int i=0;i<s.length;i++){
System.out.println(s[i]+":"+c[i]);
}
}
//选择排序
public static void selectSort(int[] arr1,String[] arr2){
for(int i = 0; i < arr1.length-1; i++){
int min = i;
for(int j = i+1; j <arr1.length ;j++){
if(arr1[j]<arr1[min]){
min = j;
}
}
if(min!=i){
swap1(arr1, i, min);
swap2(arr2, i, min);
}
}
}
//完成数组两元素间交换
public static void swap1(int[] arr,int a,int b){
int temp = arr[a];
arr[a] = arr[b];
arr[b] = temp;
}
public static void swap2(String[] arr,int a,int b){
String temp = arr[a];
arr[a] = arr[b];
arr[b] = temp;
}
}
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
public class Person {
String name;
int age;
public Person(String name, int age) {
super();
this.name = name;
this.age = age;
}
public int getAge() {
return age;
}
@Override
public String toString() {
return "Person [name=" + name + ", age=" + age + "]";
}
public static void main(String[] args) {
List<Person> persons = new ArrayList<>();
persons.add(new Person("张三", 20));
persons.add(new Person("李四", 18));
persons.add(new Person("王五", 19));
System.out.println("before sort: " + persons);
persons.sort(Comparator.comparing(Person::getAge));
System.out.println("after sort: " + persons);
/* out put
before sort: [Person [name=张三, age=20], Person [name=李四, age=18], Person [name=王五, age=19]]
after sort: [Person [name=李四, age=18], Person [name=王五, age=19], Person [name=张三, age=20]]
*/
}
public class SortDemo {
public static void main(String[] args) {
String [] s = {"张三", "李四", "王五"};
int [] c = {20, 18, 19};
int n = c.length;
for (int i = 0; i < n - 1; i++) {
for (int j = i + 1; j < n; j++) {
if (c[i] > c[j]) {
int c0 = c[i];
c[i] = c[j];
c[j] = c0;
String s0 = s[i];
s[i] = s[j];
s[j] = s0;
}
}
}
for (int i = 0; i < n; i++) {
System.out.printf("%s: %s%n", s[i], c[i]);
}
}
/* 输出
李四 : 18
王五 : 19
张三 : 20
*/
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
public class Test {
public static void main(String[] args) {
String[] s={"张三","李四","王五"};
Integer[] c={20,18,19};
HashMap<Integer,String> map = new HashMap<>();
ArrayList<Integer> list = new ArrayList();
for (int i = 0; i< c.length; i++){
map.put(c[i],s[i]);
list.add(c[i]);
}
Collections.sort(list);
for (Integer key:list) {
System.out.println("年龄:"+key+" 姓名:"+map.get(key));
}
}
}
输出结果
年龄:18 姓名:李四
年龄:19 姓名:王五
年龄:20 姓名:张三