public class BaseSort {
public void sort(int []a){
System.out.println("排序算法");
}
}
java```
SelectSort
public class SelectSort extends BaseSort{
@Override
public void sort(int []a){
int x,temp;
for (int i = 0; i <a.length-1 ; i++) {
x=i;
for (int j = i+1; j <a.length ; j++) {
if(a[x]>a[j]) {
x = j;
temp=a[x];
a[x]=a[i];
a[i]=temp;
}
}
}
System.out.print("选择排序:");
for (int i = 0; i < a.length ; i++) {
System.out.print(a[i]+" ");
}
}
}
java```
InsertSort
public class InsertSort extends BaseSort{
public void sort(int []a) {
int temp;
for (int i =0; i <a.length-1 ; i++) {
for (int j = i+1; j >0 ; j--) {
if (a[j]<a[j-1]){
temp=a[j-1];
a[j-1]=a[j];
a[j]=temp;
}
else
break;
}
}
System.out.print("插入排序:");
for (int i = 0; i < a.length; i++) {
System.out.print(a[i]+" ");
}
}
}
java```
QuickSort
public class QuickSort extends BaseSort {
public void sort(int []a,int l,int r){
if(l>r)
return;
int i=l; int j=r; int key=a[l];
while(i<j){
while(i<j&&a[j]>=key)
j--;
if(i<j){
a[i]=a[j];
i++;
}
while(i<j&&a[i]<key)
i++;
if(i<j){
a[j]=a[i];
j--;
}
}
a[i]=key;
sort(a,l,i-1);
sort(a,i+1,r);
}
}
java```
Factory
public class Factory {
private BaseSort sort;
public void setSort(BaseSort sort){
this.sort=sort;
}
public void doSort(int []a){
sort.sort(a);
}
}
java```
Test
import java.util.Scanner;
public class Tset {
public static void main(String[] args){
Scanner input = new Scanner(System.in);
int []a = new int [5];
for (int i = 0;i < 5; i++){
a[i] = input.nextInt();
}
//选择排序
Factory factory = new Factory();
BaseSort select_sort = new SelectSort();
factory.setSort(select_sort);
factory.doSort(a);
//插入排序
Factory factory2 = new Factory();
BaseSort insert_sort = new InsertSort();
factory2.setSort(insert_sort);
factory2.doSort(a);
//快速排序
Factory factory3 = new Factory();
BaseSort quick_sort = new QuickSort();
factory3.setSort(quick_sort);
factory3.doSort(a);
}
}
java```
BaseSort
public class SelectSort extends BaseSort{ @Override public void sort(int []a){ int x,temp; for (int i = 0; i <a.length-1 ; i++) { x=i; for (int j = i+1; j <a.length ; j++) { if(a[x]>a[j]) { x = j; temp=a[x]; a[x]=a[i]; a[i]=temp; } } } System.out.print("选择排序:"); for (int i = 0; i < a.length ; i++) { System.out.print(a[i]+" "); } } } java``` InsertSort
public class QuickSort extends BaseSort { public void sort(int []a,int l,int r){
} java``` Factory
import java.util.Scanner; public class Tset { public static void main(String[] args){ Scanner input = new Scanner(System.in); int []a = new int [5]; for (int i = 0;i < 5; i++){ a[i] = input.nextInt(); } //选择排序 Factory factory = new Factory(); BaseSort select_sort = new SelectSort(); factory.setSort(select_sort); factory.doSort(a); //插入排序 Factory factory2 = new Factory(); BaseSort insert_sort = new InsertSort(); factory2.setSort(insert_sort); factory2.doSort(a); //快速排序 Factory factory3 = new Factory(); BaseSort quick_sort = new QuickSort(); factory3.setSort(quick_sort); factory3.doSort(a); } } java```