-
Notifications
You must be signed in to change notification settings - Fork 2
Open
Description
public class text {
public static void main(String[] args){
Scanner scanner = new Scanner(System.in);
int a[] = new int[10];
System.out.println("请输入10个数字:");
for(int i = 0;i < 10;i++){
a[i] = scanner.nextInt();
}
Factory factory = new Factory();
BaseSort select_sort = new SelectSort();
factory.seteSort(select_sort);
factory.doSort(a);
BaseSort insert_sort = new InsertSort();
factory.seteSort(insert_sort);
factory.doSort(a);
BaseSort quick_sort = new QuickSort();
factory.seteSort(quick_sort);
factory.doSort(a);
}
}
public class BaseSort {
public void sort(int a[]){
System.out.println("排序算法");
}
}
package qlp_code;
public class Factory {
private BaseSort sort;
public void seteSort(BaseSort sort){
this.sort = sort;
}
public void doSort(int []a){
sort.sort(a);
}
}
package qlp_code;
public class InsertSort extends BaseSort{
public void sort(int a[]){
System.out.println("插入排序");
int temp,i,j;
for(j=1;j<a.length;j++) { //插入排序方法
temp = a[j];
i = j;
while(i > 0 && a[i-1] >= temp) {
a[i] = a[i-1];
i--;
}
a[i] = temp;
}
for(i = 0;i < a.length;i ++)
System.out.print(a[i]+" ");
System.out.println();
}
}
package qlp_code;
public class QuickSort extends BaseSort{
public void sort(int a[]){
System.out.println("快速排序");
qsort(a,0,a.length-1);
for(int i = 0;i < a.length;i ++)
System.out.print(a[i]+" ");
System.out.println();
}
public static void qsort(int a[], int low, int hight) {
int i, j, index;
if (low > hight) {
return;
}
i = low;
j = hight;
index = a[i]; // 用子表的第一个记录做基准
while (i < j) { // 从表的两端交替向中间扫描
while (i < j && a[j] >= index)
j--;
if (i < j)
a[i++] = a[j];// 用比基准小的记录替换低位记录
while (i < j && a[i] < index)
i++;
if (i < j) // 用比基准大的记录替换高位记录
a[j--] = a[i];
}
a[i] = index;// 将基准数值替换回 a[i]
qsort(a, low, i - 1); // 对低子表进行递归排序
qsort(a, i + 1, hight); // 对高子表进行递归排序
}
}
package qlp_code;
public class SelectSort extends BaseSort{
public void sort(int a[]){
super.sort(a);
System.out.println("选择排序");
int minIndex=0;
int temp=0;
if((a==null)||(a.length==0))
return;
for(int i=0;i<a.length-1;i++)
{
minIndex=i;//无序区的最小数据数组下标
for(int j=i+1;j<a.length;j++)
{
//在无序区中找到最小数据并保存其数组下标
if(a[j]<a[minIndex])
{
minIndex=j;
}
}
if(minIndex!=i)
{
//如果不是无序区的最小值位置不是默认的第一个数据,则交换之。
temp=a[i];
a[i]=a[minIndex];
a[minIndex]=temp;
}
}
for(int i = 0;i < a.length;i ++)
System.out.print(a[i]+" ");
System.out.println();
}
}
```javaMetadata
Metadata
Assignees
Labels
No labels