android-nuc / 17_Java_Train

17级 Android 实验室 Java 培训
12 stars 2 forks source link

1607084233陈虹宇 #27

Open 591751889 opened 6 years ago

591751889 commented 6 years ago

import java.util.Scanner;

public class Test { public static void main (String[] args){ int []a=new int[10]; Scanner scanner=new Scanner(System.in); for (int i = 0; i <10 ; i++) { a[i]=scanner.nextInt(); } Factory factory=new Factory(); BaseSort select_sort=new SelectSort();//BaseSort insert_sort=new InsertSort();BaseSort quick_sort=new QuickSort(); factory.setSort(select_sort); //factory.setSort(insert_sort);factory.setSort(quickt_sort); factory.dosort(a);

} } public class BaseSort { public void sort(int []a){ System.out.print("排序算法"); } } public class SelectSort extends BaseSort { public void sort(int []a){ for (int i = 0; i <a.length-1 ; i++) { for (int j = i+1; j <a.length ; j++) { if(a[i]>a[j]){ a[i]=a[i]+a[j]; a[j]=a[i]-a[j]; a[i]=a[i]-a[j]; } } } for (int m:a ) { System.out.print(m+" "); } } } public class InsertSort extends BaseSort { public void sort(int[] a) { for (int i = 0; i < a.length; i++) { int j = i - 1; int x = a[i]; while (j >= 0 && a[j] > x) { a[j + 1] = a[j]; j--; } if (j != i - 1) { a[j + 1] = x; } for (int m : a ) { System.out.print(m + " "); } } } } public class QuickSort extends BaseSort { void sort(int[] arr, int left, int right) { int i,j,temp; if (left < right) { i = left; j = right; temp = arr[i]; do { while (arr[j] > temp && i < j) j--; if (i < j) { arr[i] = arr[j]; i++; } while (arr[i] < temp && i < j) i++; if (i < j) { arr[j] = arr[i]; j--; } } while (i != j); arr[i] = temp; sort(arr, left, i - 1); sort(arr, i + 1, right); } } } public class Factory { private BaseSort sort; public void setSort(BaseSort sort){ this.sort=sort; } public void dosort(int []a){ sort.sort(a); } }