选择排序法
选择排序算法执行截图
![image-20210624142356230]()
(完整代码)选择排序算法基础代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
|
public class SelectionSort {
private SelectionSort(){}
public static <E extends Comparable<E>> void sort(E[] arr){
for(int i = 0 ; i < arr.length; i++){
int minIndex = i; for(int j = i; j < arr.length; j++){ if(arr[j].compareTo(arr[minIndex]) < 0) minIndex=j; }
swap(arr, i, minIndex); } }
private static <E> void swap(E[] arr, int i , int j){
E t = arr[i]; arr[i] = arr[j]; arr[j] = t; }
public static void main(String[] args){
Integer[] arr = {1, 4, 2, 3, 6, 5}; SelectionSort.sort(arr); for(int e: arr) System.out.print(e + " "); System.out.println(); } }
|
选择排序算法“优化”类排序执行截图
![image-20210624145050773]()
(完整代码)选择排序选择排序算法“优化”类成员数值排序
SelectionSort.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
|
public class SelectionSort {
private SelectionSort(){}
public static <E extends Comparable<E>> void sort(E[] arr){
for(int i = 0 ; i < arr.length; i++){
int minIndex = i; for(int j = i; j < arr.length; j++){ if(arr[j].compareTo(arr[minIndex]) < 0) minIndex=j; }
swap(arr, i, minIndex); } }
private static <E> void swap(E[] arr, int i , int j){
E t = arr[i]; arr[i] = arr[j]; arr[j] = t; }
public static void main(String[] args){
Integer[] arr = {1, 4, 2, 3, 6, 5}; SelectionSort.sort(arr); for(int e: arr) System.out.print(e + " "); System.out.println();
Student[] students = {new Student("Alice", 98), new Student("Bob", 100), new Student("Charles", 66)}; SelectionSort.sort(students); for(Student student: students) System.out.print(student + " "); System.out.println(); } }
|
(Override)覆盖方法Student.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40
|
public class Student implements Comparable<Student>{ private String name; private int score;
public Student(String name , int score){ this.name = name; this.score = score; }
@Override public int compareTo(Student another){
return this.score - another.score;
}
@Override public boolean equals(Object student){ if(this == student) return true; if(student == null) return false;
if(this.getClass() != student.getClass()) return false;
Student another = (Student)student; return this.name.equals(another.name); }
@Override public String toString(){ return String.format("Student(name: %s, score: %d)", name, score); } }
|
FROM:gylq.gitee Author:孤桜懶契
免责声明:文章中涉及的程序(方法)可能带有攻击性,仅供安全研究与教学之用,读者将其信息做其他用途,由读者承担全部法律及连带责任,本站不承担任何法律及连带责任;如有问题可邮件联系(建议使用企业邮箱或有效邮箱,避免邮件被拦截,联系方式见首页),望知悉。
点赞
https://cn-sec.com/archives/729935.html
复制链接
复制链接
-
左青龙
- 微信扫一扫
-
-
右白虎
- 微信扫一扫
-
评论