Java Bubble sorting and quick sorting implementation, java Bubble Sorting implementation
Basic Features of Bubble Sorting
(1) Sorting Algorithm Based on exchange ideas
(2) from one end, compare adjacent two elements one by one, and find that reverse order is exchange.
(3) A traversal will surely switch the largest (small) element to its final position.
Sorting Process Simulation
Code Implementation
Static void Bubble_Sort (int array []) {for (int I = 0; I <array. length; I ++) {for (int j = 0; j <array. length-i-1; j ++) {if (array [j] <array [j + 1]) {int temp = array [j]; array [j] = array [j + 1]; array [j + 1] = temp;} System. out. print ("no." + (I + 1) + "secondary sorting result:"); for (int c = 0; c <array. length; c ++) {System. out. print (array [c] + "\ t");} System. out. println ();} System. out. print ("final sorting result:"); for (int c = 0; c <array. length; c ++) {System. out. print (array [c] + "\ t ");}}
Basic Idea of quick sorting
Select an element as the intermediate element, and then compare all the elements in the table with the modified intermediate element, and move the elements in the table smaller than the intermediate element to the front of the table, move the element larger than the intermediate element to the end, and then place the intermediate element
The two parts are used as the demarcation points, so that a division is obtained. Then, the left and right parts are sorted quickly until each sub-table has only one element or empty table.
Partitioning Method
1. Selection of intermediate elements: there is no special rule for the selection of intermediate numbers as the reference point. This is the first element by default.
2. the space occupied by the intermediate element may be occupied by other elements. Therefore, you can save the value of the element to another location to free up space.
3. In this way, there is an empty position (I) in front. You can search for an element larger than the number in the middle from the end and place it on the back position.
4. At this moment, there will be an empty position (j). You can search for an element smaller than the number in the middle and place it in the front position. 4. Repeat 1 2 until the vacancy coincidence (I = j) is found on both sides ).
Sorting Process Simulation
Code Implementation
static int partition(int array[],int start,int end){ int temp=array[start]; int i=start; int j=end-1; while(i!=j){ while(i<j&&array[j]>temp){ j--; } if(i<j){ array[i]=array[j]; i++; } while(i<j&&array[i]<temp){ i++; } if(i<j){ array[j]=array[i]; j--; } } array[i]=temp; return i; } static void QuickSort(int a[],int s,int e){ if(s<e){ int i=partition(a, s, e ); QuickSort(a, s,i-1); QuickSort(a, i+1, e); } }