Several sorting algorithms, I was implemented in Java according to the pseudo-code of the algorithm, the first is the type int, and later replaced by generics.
This is the code that was written early, and now it's time to go over it and prepare for the interview.
1. Simple selection of sorting
This algorithm should be the simplest, that is, in the array from the beginning of the loop, the selection of the smallest in the front, this should be very good implementation of the nonsense
Public Static<textendsComparable<t>>t[] Genericsimpleselectionsort (t[] a) { for(inti = 0; i < a.length; i++) { intMin =i; intj = i + 1; while(J <a.length) {if(A[j].compareto (A[min]) <0) min=J; J++; } T Temp=A[i]; A[i]=A[min]; A[min]=temp; } returnA; }
It has a generic type, that is, t to integrate the comparable interface, that is, the T type can be compared
You can write a test code that adds a main function to it.
Public Static voidMain (string[] args) {random random=NewRandom (47); intN=20; Integer[] a=NewInteger[n]; for(inti = 0; i < a.length; i++) {A[i]=random.nextint (100); System.out.print (A[i]+" "); } System.out.println (); Integer[] B=Simpleselectsort.genericsimpleselectionsort (a); for(inti = 0; i < b.length; i++) {System.out.print (B[i]+" "); } }
This is just a test of 20 numbers, can be changed to 10000, and then the output commented out, calculate the run time, compare the running time of different sorting algorithms
2. Improvement of the selection sorting algorithm
Improve the simple selection of sorting algorithm, that is, each trip to select the largest, the smallest, respectively, placed in the left and right sides of the array, so the loop only to do N/2;
Public Static<textendsComparable<t>>t[] Genericselectionsort (t[] a) {intn =a.length; for(inti = 0; i < N/2; i++) { intMin =i; intMax =i; intj = i + 1; while(J < N-i) {if(A[j].compareto (A[min]) < 0) min=J; if(A[j].compareto (A[max]) > 0) Max=J; J++; } T Temp=A[i]; A[i]=A[min]; A[min]=temp; Temp= A[n-i-1]; A[n-I-1] =A[max]; A[max]=temp; } returnA; }
3. Insert Sort
Starting from the second number of the given array, the array is lined up, and the number of rows to be removed is compared to the previous ordinal number from the back forward, and the position of the number is shifted backward, knowing where to find the appropriate insertion
Well, in the language I say not good, should use the figure, but still can not draw ~ ~ or directly on the code, very simple algorithm, directly see the code should be no problem
Public Static<textendsComparable<t>>t[] Genericinsertsort (t[] a) { for(inti = 1; i < a.length; i++) { intj =i; T Temp=A[j]; while(J > 0) { if(Temp.compareto (a[j-1]) < 0) {A[j]= A[j-1]; J--; } Else { Break; }} A[j]=temp; } returnA; }
It's time to get off the clock, just to record these simple sorts.
Java implementation of sorting algorithm