The secret of invention is constant effort. --Newton
Content: bubbling, selecting, inserting sort
First, bubble sort
Principle:Compares the number of adjacent two digits to the head of the smaller number;Nthe number is going to ben-1Comparison , the first comparison to be carried outn-122 Comparisons in the firstJin the comparison, to ben-jTimes 22 comparisons. (The value of a larger element sinks down, only the remaining elements of the maximum value can be sunk again )
void Bubblesort (int[] arr) {//Bubble method to sort n-1 times for (int i=0;i<arr.length-1;i++) {//value is sinking after a larger element, only the maximum of the remaining elements can be sunk again. for ( int j=0;j<arr.length-1-i;j++) {if (arr[j]>arr[j+1]) {//to sink a value larger than the element to int temp;temp=arr[j];arr[j]=arr[j+1];arr[j+ 1]=temp;}}}}
TwoSelect Sort
principle: first, starting with the first element as a baseline, scanning in one direction, such as from left to right, toA[0]as a benchmark, next fromA[0]....a[9]To find the smallest element in theA[0]Exchange. Then move the base position to the right, repeating the action above, for example, toA[1]as a benchmark, find outA[1]~a[9]The smallest of them, andA[1]Exchange. Continues until the sort ends when the datum position is moved to the last element of the array.
<span style= "FONT-SIZE:18PX;" >void Selectsort (int[] arr) {for (int i=0;i<arr.length;i++) {//forward data from J are all lined up, so start with J to find the smallest of the remaining elements in the for (int j=i+1;j <arr.length;j++) {//With this element as the base if (Arr[i]>arr[j]) {//arr[i] with this element as the Datum int temp;temp=arr[j];arr[j]=arr[i];arr[i]=temp ;}}}} </span>
Three, Insert sort:
principle: The N-sort elements are treated as an ordered list and an unordered table, at first there is only one element of the sequence table, and the unordered list has n-1 elements, and each time the sorting process takes a number from the disordered lists and compares the ordered list. Insert it into the sequence table to make it a new ordered list.
void Insertsort (int[] arr) {for (int i=1;i<arr.length;i++) {int insertval=arr[i];//operation current element, first saved in other variable int index=i-1;// Record the first number of inserted values//find the appropriate position from the previous element of the current element, and always find the first element while (Index>=0&&insertval<arr[index]) {arr[index+1]=arr[ index];index--;//again with the previous one compared}arr[index+1]=insertval;}}
This is where we go, take your time and enjoy it
Bubble, select, insert Sort