快速排序和插入排序——我的代码
快速排序:
1 package suanfa; 2 3 import java.util.Scanner; 4 5 public class QuickSort { 6 7 public static int sortOnce(int array[],int low,int high) { 8 9 int temp=array[low]; 10 while(low<high) { 11 while(low<high&&array[high]>=temp)high--; 12 array[low]=array[high]; 13 while(low<high&&array[low]<=temp)low++; 14 array[high]=array[low]; 15 } 16 array[low]=temp; 17 return low; 18 } 19 public static void QuickSortFun(int array[],int low,int high) { 20 if(low<high) { 21 int mark = sortOnce(array,low,high); 22 QuickSortFun(array,low,mark-1); 23 QuickSortFun(array,mark+1,high); 24 } 25 } 26 27 public static void main(String[] args) { 28 int array[]=new int[10]; 29 int num=0; 30 Scanner scanner = new Scanner(System.in); 31 while(scanner.hasNext()) { 32 array[num++]=scanner.nextInt(); 33 } 34 int newArray[]=new int[num]; 35 for(int i=0;i<num;i++) { 36 newArray[i]=array[i]; 37 } 38 //int newArray[]=new int[]{6,2,5,3,7,9}; 39 QuickSortFun(newArray,0,newArray.length-1); 40 for(int j=0;j<num;j++) { 41 System.out.print(newArray[j]+" "); 42 } 43 } 44 }
插入排序:
1 package suanfa; 2 3 public class InsertSort { 4 5 public static void insertSortFun(int array[]) { 6 int length=array.length; 7 int i,j; 8 for(i=1;i<length;i++) { 9 int temp=array[i]; 10 for(j=0;j<=i;j++) { 11 if(array[j]<array[i]) { 12 continue; 13 }else { 14 break; 15 } 16 } 17 for(int k=i-1;k>=j;k--) { 18 array[k+1]=array[k]; 19 } 20 array[j]=temp; 21 } 22 } 23 24 public static void main(String[] args) { 25 int newArray[]=new int[]{6,2,5,3,7,9}; 26 insertSortFun(newArray); 27 for(int j=0;j<6;j++) { 28 System.out.print(newArray[j]+" "); 29 } 30 } 31 }