JavaNotes
Select sort
0 1 2) 3 4
The subscript 0 and other subscript comparison to select the smallest element, and then the subscript 1 followed by the other subscript to choose the smallest element in turn loop
Each element that participates in the comparison is reduced:a.length-1
for (int i = 0; i<a.length-1;i++) {
Int temp;
for (int J =i+1;j<a.length;j++) {
If (A[i]>a[j]) {
Temp=a[i];
A[I]=A[J];
A[j]=temp
}
}
}
Bubble sort: The next two elements are compared, and if the conditions are met for transposition
0 1 2) 3 4
3 and 1 are exchanged first,3 and 4 are compared without swapping,4 , and 2 for Exchange,4 and 9 do not need to exchange, and then in the next element to compare, But the last element does not need to be compared
Each element that participates in the comparison is reduced:a.length-1
The first loop maximum appears in the last
for (int i = 0; i<a.length-1;i++) {
Int temp;
for (int J =i+1;j<a.length-i-1;j++) {//-x: reduces the element per time,-1: avoid subscript bounds
If (A[i]>a[j]) {
Temp=a[i];
A[I]=A[J];
A[j]=temp
}
}
}
Insert Sort:
public static void Main (string[] args) {
TODO auto-generated Method Stub
System.out.println (" Please enter what needs to be sorted:");
Scanner input = new Scanner (system.in);
Create an array
int[] array = new INT[10];
array to accept input
for (int i = 0; i < Array.Length; i++) {
Array[i] = Input.nextint ();
}
int temp, I, j, count = 0;
System.out.println (" sorted array:");
for (i = 1; i < Array.Length; i++) {// insert all elements
temp = array[i];// places all elements with sorting into temporary variables
for (j = i-1; J >= 0 && temp < array[j]; j--) {//j-- continue to search left
Array[j + 1] = array[j];// element moves backwards
}
Array[j + 1] = temp;// Inserts an element into the appropriate position
count++;
}
System.out.print (" swapped " + Count + " times ");
System.out.println ();
for (i = 0; i < Array.Length; i++) {
System.out.print (Array[i] + "");
}
}
}
Java Note Five