1. Array sorting algorithm-bubble sort algorithm
Function: You can sort the elements in an integer array, as with the Arrays.sort method, the only difference is that the sort method can sort an array of arbitrary types.
Example:
public class P_1 {
public static void Main (String args[]) {
Int[] A = new int[] {5,2,6,7,3,9};
P_1 p = new P_1 ();
P.mysort (a);
P.showarray (a);
}
public void Mysort (int[] a) {
for (int i=1;i<a.length;i++) {//comparison number of times (25)
for (int j=0;j<a.length-1;j++) {//two numbers are compared, the large number is moved backwards.
if (A[j]>a[j+1]) {
int temp = A[j];
A[J] = a[j+1];
A[J+1] = temp;
}
}
}
}
public void Showarray (int[] a) {
for (int i=0;i<a.length;i++) {
System.out.println (A[i]);
}
}
}
2. Direct selection of sorting
Function: The direct selection of the sorting function is the same as the bubble sort, is the order of the array elements, the advantage is that the direct selection of sorting algorithm compared to the number of bubble sorting algorithm less.
Example:
public class P_1 {
public static void Main (String args[]) {
Int[] A = new int[] {5,2,6,7,3,9};
P_1 p = new P_1 ();
P.mysort (a);
P.showarray (a);
}
public void Mysort (int[] a) {
int sum = 0;
int index;
for (int i=1;i<a.length;i++) {//the number of comparisons
index = 0;
for (int j=1;j<=a.length-i;j++) {//starts with the first element of the array, the largest number is moved to the last, and is assigned to A[index].
if (A[j]>a[index]) {
index = j;
}
sum++;
}
int temp = A[a.length-i];
A[a.length-i] = A[index]; Copies the largest number to the last element of the last array.
A[index] = temp;
}
SYSTEM.OUT.PRINTLN ("Frequency" +sum); Compare 15 times in total
}
public void Showarray (int[] a) {
for (int i=0;i<a.length;i++) {
System.out.print (">" +a[i]);
}
}
}
java-Array Sorting algorithm